An introduction to

As the front end of the most easy to get started with the framework, Vue entry actually did not say what, I put a list of code, we can understand that can get started

<template>
  <div id="app">
    <h1>{{title}}</h1>
    <div>
      <input type="text" v-model="val">
      <button @click="add">add</button>
      <button @click="clear">empty</button>
    </div>
    <ul>
      <li v-for="todo in todos" :key="todo.title" :class="{done:todo.done}">
        <input type="checkbox" v-model="todo.done">
        {{todo.title}}
      </li>
    </ul>
    <p>{{active}} / {{all}}</p>
  </div>
</template>
Copy the code

<script> export default { name: "app", data() { return { title: "The snail is wet and sulky.".val: "".todos: []}; }, mounted() {const todos = localStorage.getItem("todos"); if (todos) { this.todos = JSON.parse(todos); } else { this.todos = [ { title: "Eat".done: true }, { title: "Sleep".done: false }, { title: "Write code".done: false}]; }},computed: { active() { return this.todos.filter(v= >! v.done).length; }, all() {return this.todos.length; }},watch: { todos: { deep: true, handler(todos) { localStorage.setItem("todos".JSON.stringify(todos)); }}},methods: { clear() { this.todos = this.todos.filter(v= >! v.done); }, add() {if (this.val) { this.todos.push({ title: this.val, done: false }); this.val = ""; }}}};</script> <style> li.done { color: red; text-decoration: line-through; } </style> Copy the code

The content of Vuejs is as follows. After you are familiar with this example, it is our main text. If you don’t understand the above code, please go to the official website to review it

  1. Variable rendering
  2. Render loop
  3. A class of rendering
  4. Calculate attribute
  5. The listener
  6. The binding event
  7. The life cycle

componentization

Vue single file component. The single file component of Vue is supported automatically through vue-CLI initials. create child1.vue

<template>
    <div>Child1</div>
</template>
<script>
export default {

} </script>

Copy the code

Copy the code

Used in the App

<template>
  <div id="app">
    <Child1></Child1>
  </div>
</template>

<script>
import Child1 from '@/components/Child1'
export default {
  name: "app".components:{Child1}

}

</script>
Copy the codeCopy the code

The following ushered in the first common problem, if the component is much, how they communicate with each other, do not look down upon this problem, SAO gas of the interviewer, such as me, often like to ask, let’s demonstrate the Vue component between the commonly used communication to receive

1. Parent to child components

The simplest way to pass values to parent components is through props

// App
<template>
  <div id="app">
    <Child1 :title="title1"></Child1>
  </div>
</template>

Copy the code

} </script> Copy the code

// Child1
<template>
<div>
<h2>Child2</h2>
<div>{{title}}</div>
</div>
</template>
<script>
export default {
props: ['title']

} </script>

Copy the code

Copy the code

2. The father

Vue prefers one-way data flow, so the child component needs to notify the parent component to modify the passed data and use $emit to trigger the event passed by the parent element

<template>
  <div id="app">
    <h2>Parent</h2>
    <h3>{{msg}}</h3>
    <Child1 :title="title1" @getmsg="getmsg"></Child1>
  </div>
</template>

}

</script> <style>

Copy the code

div{ border:1px red solid; padding:20px; } </style> Copy the code

// child1
<template>
<div>
<h2>Child2</h2>
<p>{{title}}</p>
<button @click="toParent">Passes to the parent element</button>
</div>
</template>
<script>
export default {
props: ['title'].methods:{
toParent(){
this.$emit('getmsg'.'Dad, I know I'm wrong.')}}

Copy the code

} </script> Copy the code

3. Sibling components

Sibling components cannot communicate directly, just bridge the parent element and let everyone experience it

4. Provide and inject ancestors and descendants

Provice /inject API for functions, functions, functions, functions, functions, functions, functions, functions, functions, functions, functions

Many open source libraries now use this API to share data across hierarchies, such as the Tabs and select of Element-UI


}

Copy the code

</script> <style> Copy the code

// Descendant element<template>

<span class="hljs-tag">&lt; <span class="hljs-name">div</span>&gt; </span> <span class="hljs-tag">&lt; <span class="hljs-name">h3</span>&gt; </span>Grandson1<span class="hljs-tag">&lt; /<span class="hljs-name">h3</span>&gt; </span> <span class="hljs-tag">&lt; <span class="hljs-name">p</span>&gt; </span> <span class=" hlJs-tag ">&lt; /<span class="hljs-name">p</span>&gt; </span> <span class="hljs-tag">&lt; /<span class="hljs-name">div</span>&gt; </span>Copy the code

</template>
<script>
export default {

<span class="hljs-attr">inject</span>:[<span class="hljs-string">'woniu'</span>]
Copy the code

Copy the code

}
</script>
Copy the code

However, provider and Inject are not responsive. If descendant elements want to notify ancestors, they need to hack. Vue1 has two methods, Dispatch and Boardcast, but vue2 is dead, we can simulate them ourselves

The principle is that you can pass this.Children to get the parent and the child, and we just recurse

5. dispatch

Getting $parent recursively is simple

<button @click="Dispatch ('dispatch',' Hello GrandGrandChild1')">dispatch</button>
Copy the codeCopy the code
  methods: {
dispatch(eventName, data) { <span class="hljs-keyword">let</span> parent = <span class="hljs-keyword">this</span>.$parent <span Class ="hljs-comment"> <span class="hljs-keyword">while</span> (parent) {<span $emit(eventName,data) class="hljs-keyword">if</span> (parent) {<span class="hljs-comment"> $parent}<span class="hljs-keyword">else</span>{<span class="hljs-keyword">else</span> class="hljs-keyword">break</span> } } }Copy the code

Copy the code

}
Copy the code

Notice that it only passes up, not affecting other elements

6. boardcast

Like Dispatch, $children is recursively acquired to broadcast to all child elements

<button @click="$boardcast (' boardcast ', 'I am Child1')">Broadcast child element</button>
Copy the codeCopy the code
function boardcast(eventName, data){
  this.$children.forEach(child= > {
    // The child element fires $emit
    child.$emit(eventName, data)
    if(child.$children.length){
      // Recursive call to modify this to refer to the child via call
      boardcast.call(child, eventName, data)
    }
  });
}
{
  methods: {
$boardcast(eventName, data) {
  boardcast.call(<span class="hljs-keyword">this</span>,eventName,data)
}
Copy the code

Copy the code

}}Copy the code

7. Mount Dispatch and Boardcast globally

If you want to use it, you need to use your own internal theorems dispatch and boardcast too tired, we mount it to the Vue prototype chain, isn’t it very high, find main.js

Vue.prototype.$dispatch =  function(eventName, data) {
  let parent = this.$parent
  // Find the parent element
  while (parent ) {
    if (parent) {
      // The parent element fires with $emit
      parent.$emit(eventName,data)
      // Find the parent element recursively
      parent = parent.$parent
    }else{
      break}}}

Vue.prototype.children.forEach(child= > { // The child element firesemit(eventName, data) if(child.$children.length){ // Recursive call to modify this to refer to the child via call boardcast.call(child, eventName, data) } }); }

Copy the code

Copy the code

So the components can be used directly without pressure

8. Irrelevant component: event-bus

If the two components have nothing to do with each other, we can only do this using subscription publishing mode and mount it on vue.protyType. Let’s try it. We call this mechanism bus mechanism, which is the much-loved event-bus


class Bus{
  constructor() {/ / {
    // eventName1:[fn1,fn2],
    // eventName2:[fn3,fn4],
    // }
    this.callbacks = {}
  }
  $on(name,fn){
    this.callbacks[name] = this.callbacks[name] || []
    this.callbacks[name].push(fn)
  }
  $emit(name,args){
    if(this.callbacks[name]){
      // The existence iterates through all the callback
      this.callbacks[name].forEach(cb= > cb(args))
    }
  }
}
Copy the code

Vue.prototype.$bus = new Bus() Copy the code

use

/ / use
eventBus(){
    this.$bus.$emit('event-bus'.'test eventBus')}/ / to monitor
this.$bus.$on("event-bus",msg=>{
    this.msg = 'Receive event-bus message :'+ msg
})
Copy the codeCopy the code

In fact, Vue itself is a subscription publishing implementation, so we can delete the Bus class and create an empty Vue instance


Vue.prototype.$bus = new Vue()
Copy the codeCopy the code

9. vuex

fromVue Stubborn Bronze – Gateway and componentized communication G