做为前端最容易上手的框架,Vue入门其实没啥说的,我放一段清单的代码,你们能看懂就说明能上手了javascript
<template>
<div id="app"> <h1>{{title}}</h1> <div> <input type="text" v-model="val"> <button @click="add">添加</button> <button @click="clear">清空</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> <script> export default { name: "app", data() { return { title: "蜗牛老湿很骚气", val: "", todos: [] }; }, mounted() { const todos = localStorage.getItem("todos"); if (todos) { this.todos = JSON.parse(todos); } else { this.todos = [ { title: "吃饭", done: true }, { title: "睡觉", done: false }, { title: "写代码", 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> 复制代码
大概包含的内容以下,对这个例子熟悉后,才是咱们的正文,若是上面代码有没看懂的地方,快去Vuejs官网回顾一下吧css
Vue单文件组件。Vue的单文件组件相信你们都体验过,经过vue-cli初始化的项目自动就支持了,新建Child1.vuehtml
<template>
<div>Child1</div>
</template>
<script> export default { } </script>
复制代码
App中使用前端
<template>
<div id="app">
<Child1></Child1>
</div>
</template>
<script> import Child1 from '@/components/Child1' export default { name: "app", components:{Child1} } </script>
复制代码
下面就迎来了第一个常见问题, 若是组件多了,他们之间如何通讯唠嗑呢,不要小看这个问题,骚气的面试官,好比我,就常常喜欢问,下面咱们来演示一下Vue组件之间经常使用的通讯收件vue
父子组件传值,最简单的就是经过props传递,话很少说看代码java
// App
<template>
<div id="app">
<Child1 :title="title1"></Child1>
</div>
</template>
<script> import Child1 from '@/components/Child1' export default { name: "app", data(){ return { title1:'我是你爸爸' } }, components:{Child1} } </script>
复制代码
// Child1
<template>
<div>
<h2>Child2</h2>
<div>{{title}}</div>
</div>
</template>
<script> export default { props:['title'] } </script>
复制代码
Vue更推荐单向数据流,因此子组件像修改传递的数据,须要通知父组件来修改,使用$emit触发父元素传递的事件git
<template>
<div id="app">
<h2>Parent</h2>
<h3>{{msg}}</h3>
<Child1 :title="title1" @getmsg="getmsg"></Child1>
</div>
</template>
<script> import Child1 from '@/components/Child1' export default { name: "app", data(){ return { msg:'', title1:'我是你爸爸' } }, methods:{ getmsg(msg){ console.log(msg) this.msg = msg } }, components:{Child1} } </script>
<style> div{ border:1px red solid; padding:20px; } </style>
复制代码
// child1
<template>
<div>
<h2>Child2</h2>
<p>{{title}}</p>
<button @click="toParent">传递到父元素</button>
</div>
</template>
<script> export default { props:['title'], methods:{ toParent(){ this.$emit('getmsg','爸爸,我知道错了') } } } </script>
复制代码
兄弟组件不能直接通讯,只须要父元素搭个桥便可,你们本身体验便可github
props一层层传递,爷爷给孙子还好,若是嵌套了五六层还这么写,感受本身就是一个沙雕,因此这里介绍一个 稍微冷门的API, provice/inject,相似React中的上下文,专门用来跨层级提供数据面试
如今不少开源库都使用这个api来作跨层级的数据共享,好比element-ui的tabs 和 selectvuex
<script> import Child1 from '@/components/Child1' export default { name: "app", provide:{ woniu:'我是蜗牛' }, components:{Child1} } </script>
<style> 复制代码
// 子孙元素
<template>
<div>
<h3>Grandson1</h3>
<p>
祖先元素提供的数据 : {{woniu}}
</p>
</div>
</template>
<script> export default { inject:['woniu'] } </script>
复制代码
可是provider和inject不是响应式的,若是子孙元素想通知祖先,就须要hack一下,Vue1中有dispatch和boardcast两个方法,可是vue2中被干掉了,咱们本身能够模拟一下
原理就是能够经过this.children来获取父组件和子组件,咱们递归一下就能够了
递归获取$parent便可 比较简单
<button @click="dispatch('dispatch','哈喽 我是GrandGrandChild1')">dispatch</button>
复制代码
methods: {
dispatch(eventName, data) {
let parent = this.$parent
// 查找父元素
while (parent ) {
if (parent) {
// 父元素用$emit触发
parent.$emit(eventName,data)
// 递归查找父元素
parent = parent.$parent
}else{
break
}
}
}
}
复制代码
注意只向上传递了,并无影响别的元素
和dispatch相似,递归获取$children 来向全部子元素广播
<button @click="$boardcast('boardcast','我是Child1')">广播子元素</button>
复制代码
function boardcast(eventName, data){
this.$children.forEach(child => {
// 子元素触发$emit
child.$emit(eventName, data)
if(child.$children.length){
// 递归调用,经过call修改this指向 child
boardcast.call(child, eventName, data)
}
});
}
{
methods: {
$boardcast(eventName, data) {
boardcast.call(this,eventName,data)
}
}
}
复制代码
想用的时候,须要本身组件内部定理dispatch和boardcast太烦了,咱们挂载到Vue的原型链上,岂不是很high,找到main.js
Vue.prototype.$dispatch = function(eventName, data) {
let parent = this.$parent
// 查找父元素
while (parent ) {
if (parent) {
// 父元素用$emit触发
parent.$emit(eventName,data)
// 递归查找父元素
parent = parent.$parent
}else{
break
}
}
}
Vue.prototype.$boardcast = function(eventName, data){
boardcast.call(this,eventName,data)
}
function boardcast(eventName, data){
this.$children.forEach(child => {
// 子元素触发$emit
child.$emit(eventName, data)
if(child.$children.length){
// 递归调用,经过call修改this指向 child
boardcast.call(child, eventName, data)
}
});
}
复制代码
这样组件里直接就能够用了 无压力
若是俩组件没啥关系呢,咱们只能使用订阅发布模式来作,而且挂载到Vue.protytype之上,咱们来试试,咱们称呼这种机制为总线机制,也就是喜闻乐见的 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]){
// 存在 遍历全部callback
this.callbacks[name].forEach(cb=> cb(args))
}
}
}
Vue.prototype.$bus = new Bus()
复制代码
使用
// 使用
eventBus(){
this.$bus.$emit('event-bus','测试eventBus')
}
// 监听
this.$bus.$on("event-bus",msg=>{
this.msg = '接收event-bus消息:'+ msg
})
复制代码
其实自己Vue就是一个订阅发布的实现,咱们偷个懒,把Bus这个类能够删掉,新建一个空的Vue实例就能够啦
Vue.prototype.$bus = new Vue()
复制代码
总结了那么多,其实最佳实践就是vuex,这个后面再专门写文章学习吧
看完这个文章,Vue组件化通讯应该就难不住你了,也恭喜你度过青铜,正式迈入Vue秩序白银级别