hauge
hauge

Reputation: 1535

Update component when prop changes

How do I force a component to re-render when a prop changes?

Say I have a component which holds:

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

And I have my data object like so:

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

Then with a click on a button i would like to change the settings of the prop passed, and the component should re-render, something like

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

And a method like

changeLayout() {
        this.layoutSetting = 'small';
    },

This changed the data object, but it doesnt re-render the component with the changed prop?

Upvotes: 5

Views: 8313

Answers (1)

Bert
Bert

Reputation: 82439

When you pass a property that is defined as camelCased in the component, you need to use the kebab-cased property name in the template.

<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/[email protected]/dist/vue.js"></script>

<div id="app">
  <test-sub-component :layout-setting="layoutSetting"></test-sub-component>
  <button @click="changeLayout">Change Layout</button>
</div>

Upvotes: 1

Related Questions