#vue中通过v-on、v-bind来更方便向'孙子'组件传数据和方法#
index.vue(爷组件) -> cp1.vue(父组件) -> cp2.vue(孙组件)
期望:index组件的方法和数据可以直接给cp2使用。
index.vue文件:
我是父组件:
<script>
import cp1 from './1.vue'
export default {
name: 'index',
components: {
cp1
},
data() {
return {
money: 10000,
age: 18
}
},
onReady() {},
methods: {
eating () {
console.log('have dinner')
},
useMoney () {
this.money -= 100
}
},
}
</script>
cp1组件:
我是1组件:
<script>
import cp2 from './2.vue'
export default {
name: 'cp-1',
components: {
cp2
},
data() {
return {}
},
methods: {},
}
</script>
cp2组件:
组件2直接越过1组件。通过$attrs来获取index组件的数据:{{$attrs.money}}
组件2直接越过1组件。通过$attrs来获取index组件的数据:{{$attrs.age}}
<script>
export default {
name: 'cp-2',
data() {
return {}
},
methods: {
handleClick () {
this.$listeners.eating()
},
handleClick2 () {
this.$listeners.useMoney()
}
},
}
</script>
vue中v-on可以直接把监听的事件传递给子组件,也就是methods里面的方法等。
同时v-bind可以把属性data里面的数据,传递给子组件。这种方式,子组件件是可以更改父组件里面的数据的。