如何将值传递给vue实例?

时间:2020-08-15 10:11:19

标签: javascript vue.js vuejs2 vue-component

我想将Web组件中的值传递给vue实例,我想使用它来引用html.erb文件, 这是我要在其上安装vue实例的元素:

    <div id="app" :purchaseId="1">

将其传递给vue实例,但似乎不起作用,该vue实例在main.js中声明为:

export default new Vue({
  store,
  vuetify,
  render: h => h(App),
  data: {
    purchaseId: null
  },
  methods: {
    setJson(payload) {
      console.log("payload", payload);
      this.purchaseId = payload;
    }
  }
}).$mount("#app");

在此之后,我想传递给它的子组件,谁能告诉我该怎么做

1 个答案:

答案 0 :(得分:2)

我看到您应该将该属性而不是data属性绑定到该方法,并将来自rails的数据作为参数传递: 第一个解决方案:

  <div id="app" :purchaseId="setJson(1)">

  <div id="app" :purchaseId="setJson(<%= purchaseId %>)">

export default new Vue({
  store,
  vuetify,
  render: h => h(App),
  data: {
    purchaseId: null
  },
  methods: {
    setJson(payload) {
      console.log("payload", payload);
      this.purchaseId = payload;
    }
  }
}).$mount("#app");

第二个解决方案:

尝试使用纯js通过$ refs和getAttribute方法获取该值:

<div id="app" ref="app" purchaseId="<%= purchaseId %>">
export default new Vue({
  store,
  vuetify,
  render: h => h(App),
  data: {
    purchaseId: null
  },
  methods: {
    setJson(payload) {
      console.log("payload", payload);
      this.purchaseId = payload;
    }
  },
 mounted(){
    let payload=this.$refs.app.getAttribute('purchaseId');
    this.purchaseId = payload;

  }
}).$mount("#app");