【问题标题】:How to change vue.js components data outside scope如何在范围外更改 vue.js 组件数据
【发布时间】:2019-12-18 07:25:30
【问题描述】:

我想在默认导出语句之外更改 vue.js 数据。鉴于下面的示例,我将如何去做?

<template>
    <div>
        <h6 class="font-weight-normal mb-3">{{ name }}</h6>
    </div>
</template>

<script>
export default {
    data() {
        return {
            name: ""
        }
    }
}

let changeName = (name) => {
    //How do I change the name data property here
}
</script>

【问题讨论】:

标签: vue.js vuejs2 vue-component


【解决方案1】:

如果您将组件分配给变量/常量,您应该能够简单地触发数据对象的代理设置器或使用组件级方法。

const component = new Vue({
  data() {
    return {
      name: "Initial value."
    }
  },
  
  methods: {
    changeName(newName) {
      this.name = newName;
    }
  }
});

// Mount it to an element (for demo purposes)
component.$mount('#app');

document.getElementById('btn-setter').onclick = function() {
  component.name = 'Changed with SETTER';
};

document.getElementById('btn-method').onclick = function() {
  component.changeName('Changed with METHOD');
};

// Uncomment this to start exporting it.
// export default component;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <h6 class="font-weight-normal mb-3">{{ name }}</h6>
  
  <button id="btn-setter">Change with setter</button>
  <button id="btn-method">Change with method</button>
</div>

【讨论】:

    【解决方案2】:

    您可以在组件之外的页面中编写任何您想要的函数(或导出语句),但您需要在您的methods 部分或组件中的某个位置调用它。我将它用于创建默认值的函数,而不是从外部导入它们,只需编写一个函数 initVal = () =&gt; someVal 然后在 datacomputed 或某处引用 initVal (没有这个)。

    【讨论】:

      猜你喜欢
      • 2013-07-13
      • 2023-02-19
      • 2017-09-01
      • 2016-05-09
      • 1970-01-01
      • 2017-12-31
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      相关资源
      最近更新 更多