vue组件对vue数据对象的更改做出反应

时间:2017-09-19 03:37:57

标签: javascript vue.js vue-component

我在服务器端生成了一些原始html,我希望使用Vue框架进行反应性更新。

我首先认为v-html会完成这项工作,但这并不起作用,因为v-html对vue数据值的变化没有反应。

显然,组件是实现此目的的一种方式,但是我无法弄清楚如何将组件的内容链接到Vue对象的数据。

假设我有一个名为table_html的Vue数据值,这是一个准备好在页面中呈现的表,我将如何创建一个能够对table_html中的更改做出反应的组件?

这里有一些不起作用的东西。 (似乎在调用self = this时,self成为vue组件,如何引用其父组件?即page对象?)

page = new Vue({

  components: {
    'table-element': {
      template: "<div>{{ table_html }}</div>",
      data: function() {
        self = this; // References the component, not the parent

        return self.table_html // How to reference the Vue bound data?

      }
    }
  },

  el: "#container",

  data: {
    table_html: "<table>...table contents </table>
  }

2 个答案:

答案 0 :(得分:0)

您可以使用props将数据从parent传递到child组件。 更多细节可以在官方文档中找到。 https://vuejs.org/v2/guide/components.html#Props

&#13;
&#13;
// Component declaration
Vue.component('table-element', {
    // declare the props
    props: ['tableHtml'],
    
    // just like data, the prop can be used inside templates
    // and is also made available in the vm as this.message
    template: '<div>{{ tableHtml }}</div>',
    
    data: function() {    
        self = this; 
        return self.tableHtml;
});


page = new Vue({

  el: "#container",

  data: {
    table_html: "<table>...table contents </table>
  }
  
 
})
&#13;
<div id="container">
  <table-element v-bind:table-html = "table_html" ></table-element>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

1)props可以是通信父子组件或记录器 - 直接注册子项的良好解决方案。请记住,props是一个可变数据,作为vue instante中的数据。
2)您在外部js文件中将数据存储在全局范围内的javascript中,如果您在html代码体系结构中将数据传递给后代子项,那么这不是一个优雅的解决方案。
3)您可以使用vuex来控制组件体系结构中的数据通信。

相关问题