prop 和 $emit
父组件通过props的方式向子组件传递数据,而通过$emit 子组件可以向父组件通信。
<!-- 父组件 father.vue-->
<template>
<div class="father">
<son :msg="msg" @changeMsg="changeMsg"></son>
</div>
</template>
<script>
import son from './son.vue'
export default {
components: { son },
data() {
return {
msg: '我是父组件的msg'
}
},
methods:{
changeMsg(msg){
this.msg = msg
}
}
</script>
<!-- 子组件 son.vue -->
<template>
<div class="son">
<p>{{ msg }}</p>
<button @click="handleClick">修改父组件msg</button>
</div>
</template>
<script>
export default {
props: {
msg: String
},
methods: {
handleClick(){
this.$emit('changMsg', '修改msg')
}
}
}
provide 和 inject
多个组件嵌套时,顶层组件provide提供变量,后代组件都可以通过inject来注入变量。这种方式就是vue中依赖注入,该方法用于 祖孙组件之间 的通信。就不用一层一层的传递数据了。
// 祖先组件 提供foo
//第一种
export default {
name: "father",
provide() {
return {
foo: 'hello'
}
},
}
//第二种
export default {
name: "father",
provide: {
foo:'hello~~~~'
},
}
//后代组件 注入foo, 直接当做this.foo来用
export default {
inject:['foo'],
}
vuex
路由
slot
ref / $ref
// 父组件 app.vue
<template>
<component-a ref="comA"></component-a>
</template>
<script>
export default {
mounted () {
const comA = this.$refs.comA;
console.log(comA.name); // Vue.js
comA.sayHello(); // hello
}
}
</script>
// 子组件 A.vue
export default {
data () {
return {
name: 'Vue.js'
}
},
methods: {
sayHello () {
console.log('hello')
}
}
}
v-model 和 .sync
v-model 是用来在表单控件或者组件上创建双向绑定的,他的本质是 v-bind 和 v-on 的语法糖,在一个组件上使用 v-model,默认会为组件绑定名为 value 的 prop 和名为 input 的事件。
当我们组件中的某一个 prop 需要实现上面所说的”双向绑定“时,v-model 就能大显身手了。有了它,就不需要自己手动在组件上绑定监听当前实例上的自定义事件,会使代码更简洁。