我想在默认导出语句之外更改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>
答案 0 :(得分: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>
答案 1 :(得分:0)
您可以在组件外部的页面(或export语句)中编写所需的任何函数,但是您需要在methods
部分或组件中的某个位置调用它。我将其用于创建默认值的函数,而不是从外部导入它们,只需编写一个函数initVal = () => someVal
,然后在data
或computed
或某个地方引用initVal
中编写(不)。