prop 更改时更新组件

hau*_*uge 5 vue.js vuejs2

当 prop 发生变化时,如何强制组件重新渲染?

假设我有一个包含以下内容的组件:

<test-sub-component :layoutSetting="layoutSetting"></test-sub-component>
Run Code Online (Sandbox Code Playgroud)

我的数据对象如下所示:

 data() {
  return {
    layoutSetting: 'large'
  }
},
Run Code Online (Sandbox Code Playgroud)

然后,通过单击按钮,我想更改传递的道具的设置,并且组件应该重新渲染,例如

<button @click="changeLayout">Change Layout</button>
Run Code Online (Sandbox Code Playgroud)

和一个像这样的方法

changeLayout() {
        this.layoutSetting = 'small';
    },
Run Code Online (Sandbox Code Playgroud)

这更改了数据对象,但它不会使用更改后的 prop 重新渲染组件?

Ber*_*ert 1

当您传递在组件中定义为驼峰式命名的属性时,您需要在模板中使用短横线命名的属性名称。

<test-sub-component :layout-setting="layoutSetting"></test-sub-component>
Run Code Online (Sandbox Code Playgroud)

<test-sub-component :layout-setting="layoutSetting"></test-sub-component>
Run Code Online (Sandbox Code Playgroud)
console.clear()

Vue.component("test-sub-component", {
  props: ["layoutSetting"],
  template:`<div>{{layoutSetting}}</div>`
})

new Vue({
  el: "#app",
  data() {
    return {
      layoutSetting: 'large'
    }
  },
  methods: {
    changeLayout() {
      this.layoutSetting = 'small';
    },
  }
})
Run Code Online (Sandbox Code Playgroud)