Fra*_*ank 1 javascript onsen-ui vue.js
我正在使用带有框架的vue-cordova-webpack(https://github.com/OnsenUI/vue-cordova-webpack)模板项目Onsen UI.
我有一个我从父母那里调用的子组件,如下所示:
<template>
<!-- ... -->
<child :value1="value1"
:value2="value2">
</child>
<!-- ... -->
</template>
Run Code Online (Sandbox Code Playgroud)
在我有的子组件中:
<template>
<!-- ... -->
<v-ons-search-input v-model="mutableValue1"> </v-ons-search-input>
<v-ons-checkbox v-model="mutableValue2"> </v-ons-checkbox>
<!-- ... -->
</template>
export default {
props: ['value1', 'value2'],
name: 'child',
data() {
return {
mutableValue1: this.value1,
mutableValue2: this.value2,
};
}
};
Run Code Online (Sandbox Code Playgroud)
现在,正如您所看到的,当用户更改和组件的值时,会更新mutableValue1和mutableValue2变量.<v-ons-search-input><v-ons-checkbox>
(我介绍了这些mutableValue1和mutableValue2变量以避免[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders...警告)
我在父视图中需要这些值.目前我在访问this.value1和this.value2父视图时没有更新这些值.
我怎样才能做到这一点?
谢谢
你有几个选择.首先,您可以使用参考访问所有子道具:
// parent-component.vue
<template>
<child :value1="value1"
:value2="value2"
ref="my-child">
</child>
</template>
<script>
export default () {
name: 'parent component',
methods: {
getChildProps() {
console.log(this.$refs['my-child'].mutableValue1); // outputs mutableValue
},
},
};
<script>
Run Code Online (Sandbox Code Playgroud)
第二个选项是在发生更改时从子组件发出事件.然后在父组件中监听它:
// parent-component.vue
<template>
<child :value1="value1"
:value2="value2"
@change=doSomething>
</child>
</template>
<script>
export default () {
name: 'parent component',
methods: {
doSomething(payload) {
console.log(payload); // outputs mutableValue
},
},
};
<script>
// child-component.vue
<template>
<v-ons-search-input v-model="mutableValue1"></v-ons-search-input>
</template>
<script>
export default {
props: ['value1', 'value2'],
name: 'child',
data() {
return {
mutableValue1: this.value1,
};
};
watch: {
mutableValue1(val) {
this.$emit('change', mutableValue1);
},
},
};
</script>
Run Code Online (Sandbox Code Playgroud)
以下是第二个选项的示例.
| 归档时间: |
|
| 查看次数: |
1161 次 |
| 最近记录: |