在Nuxt中,父子组件间的数据传递数据有两种方法,如下
1、 props
父组件通过props将数据传递给子组件,子组件通过props接收数据。代码如下:
<template><div><ChildLeft :msg="msg"></ChildLeft></div>
</template><script>
import ChildLeft from '@/components/child-left.vue'export default {components: {ChildLeft },data () {return {msg: 'hello'}}
}
</script>
在子组件中通过props接收msg数据:
<template><div>{{ msg}}</div>
</template><script>
export default {props: {msg: {type: String,required: true}}
}
</script>
2、$emit
子组件通过$emit向父组件派发事件,同时将需要传递的数据作为参数。在父组件中使用@事件名监听子组件派发的事件,通过$event获取子组件传递的数据。代码如下:
<template><div><ChildLeft @update-msg="setMsg"></ChildLeft ><p>{{ msg}}</p></div>
</template><script>
import ChildLeft from '@/components/child-left.vue'export default {components: {ChildLeft },data () {return {msg: ''}},methods: {setMsg(msg) {this.msg= msg}}
}
</script>
在子组件中通过$emit派发事件,同时将需要传递的数据作为参数传递:
<template><div><button @click="updateMsg">update msg</button></div>
</template><script>
export default {methods: {updateMsg() {this.$emit('update-msg', 'new msg')}}
}
</script>
在父组件中监听update-msg事件,通过$event获取子组件传递的数据。在本例中,需要将子组件传递的数据作为参数传递给setMsg方法。
在实际开发中我们有时候需要直接帮传过来值作为model,用此方法导致参数未双向绑定,所以会报一下错误
v-model cannot be used on a prop, because local prop bindings are not writable。
我们可以参考Nuxt:父传子,将字段作为v-model异常-CSDN博客 此方法即可解决此问题