营销公司业务范围/windows优化软件哪个好
关于非父子之间传值以及父子之间传值的问题!
父组件向子组件传值:
父传子通过props进行传值;
下面直接上代码:
父组件:
<template><div>父组件:<input type="text" v-model="name"><br><br><!-- 引入子组件 --><child :inputName="name"></child></div>
</template>
<script>import child from './child'export default {components: {child},data () {return {name: ''}}}
</script>
子组件:
<template><div>子组件:<span>{{inputName}}</span></div>
</template>
<script>export default {// 接受父组件的值props: {inputName: String,required: true}}
</script>
子传父通过emit进行传值:
下面是代码块:
父组件:
<template><div>父组件:<span>{{name}}</span><br><br><!-- 引入子组件 定义一个on的方法监听子组件的状态--><child v-on:childByValue="childByValue"></child></div>
</template>
<script>import child from './child'export default {components: {child},data () {return {name: ''}},methods: {childByValue: function (childValue) {// childValue就是子组件传过来的值this.name = childValue}}}
</script>
子组件:
<template><div>子组件:<span>{{childValue}}</span><!-- 定义一个子组件传值的方法 --><input type="button" value="点击触发" @click="childClick"></div>
</template>
<script>export default {data () {return {childValue: '我是子组件的数据'}},methods: {childClick () {// childByValue是在父组件on监听的方法// 第二个参数this.childValue是需要传的值this.$emit('childByValue', this.childValue)}}}
</script>
非父子组件之间传值:通过this. $eventBus. $on()加上this. $eventBus. $emit()配合使用;
其中on是监听事件;emit是派发事件;