将数据从刀片传递到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>
,

我只需要像这样通过categoryprops传递给内联模板组件:

@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与孩子进行交流。