如何解决将数据从刀片传递到Vue,并使父子保持同步?
我知道在Vue中,父母应该通过props更新孩子,孩子应该通过events更新孩子。
假设这是我的父组件.vue
文件:
<template>
<div>
<my-child-component :category="category"></my-child-component>
</div>
</template>
<script>
export default {
data: {
return {
category: 'Test'
}
}
}
</script>
当我更新此组件中的category
数据时,它也会更新my-child-component
中的类别道具。
现在,当我想在Laravel中使用Vue时,通常会使用一个内联模板,并将刀片中的值直接传递给我的组件(例如,在https://stackoverflow.com/a/49299066/2311074中也建议这样做)。
因此,上面的示例我的my-parent-component.blade.PHP
可能看起来像这样:
@push('scripts')
<script src="/app.js"></script>
@endpush
<my-parent-component inline-template>
<my-child-component :category="{{ $category }}"></my-child-component>
</my-parent-component>
但是现在my-parent-component
不知道category
的数据。基本上只有孩子知道category
,并且父母与孩子之间对此没有任何沟通。
如何在不中断父子通讯的情况下从刀片传递数据?
解决方法
您对this answer的引用与您要查找的完全不同!
他绑定:userId
组件的example
道具,但不绑定父组件,或者用简单的词绑定:使用example vue
的任何模板都可以传递string
道具或将:userId
属性绑定到字符串变量。以下是类似的内容:
<example :userId="{{ Auth::user()->id }}"></example>
OR
<example :userId="'some test string'"></example>
因此,您应该将{{ $category }}
分配给数据变量,而应绑定到对父级没有影响的子组件prop
。
在以下代码段中,您仅绑定字符串,而是绑定数据键:
<my-child-component :category="{{ $category }}"></my-child-component>
更新
请参阅以下示例,该示例将在 3秒
后更改h1
标题
// HelloWorld.vue
<template>
<app-name :name="appName" @appNameChanged="appName = $event"></app-name>
</template>
<script>
export default {
props: ['name'],data() {
return {
appName: null
}
},mounted() {
// NOTE: since Strings are immutable and thus will assign the value while objects and arrays are copied by reference
// the following is just for the purpose of understanding how binding works
this.appName = this.name;
}
}
</script>
呈现应用标题的模板,或者您可以说子组件
// AppName.vue
<template>
<h1>{{ name }}</h1>
</template>
<script>
export default {
props: ['name'],mounted() {
setTimeout(() => {
this.$emit('appNameChanged','Change App')
},3000);
}
}
</script>
这是welcome.blade.php
<div id="app">
<hello-world :name="'Laravel App'"></hello-world>
</div>
,
我只需要像这样通过category
将props
传递给内联模板组件:
@push('scripts')
<script src="/app.js"></script>
@endpush
<my-parent-component :initcategory="{$category}}" inline-template>
<my-child-component v-model="category"></my-child-component>
</my-parent-component>
在my-parent-component
中,我必须设置道具并使用create方法进行初始化:
export default {
props: {
initcategory: '',},data() {
return {
category: '',};
},created(){
this.category = this.initcategory;
}
}
现在,我的my-parent-component
完全了解该类别,并且可以像往常一样使用props
和$emit
与孩子进行交流。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。