【问题标题】:Update component when prop changesprop 更改时更新组件
【发布时间】:2017-11-30 20:49:26
【问题描述】:

如何在道具更改时强制组件重新渲染?

假设我有一个组件:

<test-sub-component :layoutSetting="layoutSetting"></test-sub-component>

我的数据对象是这样的:

 data() {
  return {
    layoutSetting: 'large'
  }
},

然后单击一个按钮,我想更改传递的道具的设置,并且组件应该重新渲染,类似于

<button @click="changeLayout">Change Layout</button>

还有一个像

这样的方法
changeLayout() {
        this.layoutSetting = 'small';
    },

这改变了数据对象,但它没有用改变的道具重新渲染组件?

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

    当你传递一个在组件中定义为camelCased的属性时,你需要在模板中使用kebab-cased的属性名。

    <test-sub-component :layout-setting="layoutSetting"></test-sub-component>
    

    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';
        },
      }
    })
    <script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
    
    <div id="app">
      <test-sub-component :layout-setting="layoutSetting"></test-sub-component>
      <button @click="changeLayout">Change Layout</button>
    </div>

    【讨论】:

      猜你喜欢
      • 2018-05-21
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 2017-11-18
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 2021-01-14
      相关资源
      最近更新 更多