VueJS在单个文件中选择组件



我绝望了。我完全不知道如何将html "select"标签外包给单个Vue组件文件。我尝试了很多不同的方法,但不幸的是,我从来没有让它工作。

用户组件:

<custom-select :id="'continent'" :selected="user.continent" :options="continents" @change.native="changedContinent" class="some css classes" />
export default {
props: ['user'],
components: {
CustomSelect,
},
data() {
return {
continents: [
{ value: 'africa', text: 'Africa' },
{ value: 'america-north', text: 'America (North)' },
{ value: 'america-south', text: 'America (South)' },
{ value: 'asia', text: 'Asia' },
{ value: 'australia', text: 'Australia' },
{ value: 'europe', text: 'Europe' }
]
};
},
methods: {
updateUser() {
axios.post('/updateUser', this.user).then(() => {});
},
changedContinent() {
// Do something with the new selected continent like changing background relative to the selected continent
}
}
};

CustomSelect:

<template>
<select v-model="selected" class="some css classes">
<option v-for="option in options" :key="option.value" :value="option.value">{{ option.text }}</option>
</select>
</template>
<script>
export default { props: ['id', 'selected', 'label', 'options'] };
</script>

每当我改变选择的值,它应该更新用户。但是,它会抛出以下错误:

避免直接改变prop,因为该值将被覆盖当父组件重新呈现时。相反,使用数据或基于道具值的计算属性。道具发生变异:"selected">

但是我不知道如何处理这个。有人能帮帮我吗?
提前感谢!

如错误信息所示,'为避免直接改变prop,请使用data或computed属性…'

我修改了你的代码来创建我的测试环境中的组件(Vue 2使用Vue CLI),并将CustomSelect绑定到一个新的数据属性'selectedContinent'从'selected'道具初始化。我还通过自定义事件更新父组件(在您的情况下的用户组件)。这是我的组件。参见Vue自定义事件文档

我CustomSelect。vue组件:

<template>
<div class="custom-select">
<select v-model="selectedContinent" class="" v-on:change="changeContinent">
<option v-for="option in options" :key="option.value" :value="option.value">{{ option.text }}</option>
</select>
</div>
</template>
<script>
export default {
props: ['id', 'selected', 'label', 'options'],
data() {
return {
selectedContinent: this.selected
}
},
methods: {
changeContinent() {
//console.log('changeContinent: ' + this.selectedContinent);
this.$emit('change-continent-event', this.selectedContinent);
}
}
}
</script>

我的父母。value组件(你的用户):

<template>
<div class="parent">
<custom-select :id="'continent'" :selected="user.continent" :options="continents"
v-on:change-continent-event="changedContinent" />
</div>
</template>
<script>
import CustomSelect from './CustomSelect.vue'
export default {
props: ['user'],
components: {
CustomSelect,
},
data() {
return {
continents: [
{ value: 'africa', text: 'Africa' },
{ value: 'america-north', text: 'America (North)' },
{ value: 'america-south', text: 'America (South)' },
{ value: 'asia', text: 'Asia' },
{ value: 'australia', text: 'Australia' },
{ value: 'europe', text: 'Europe' }
]
};
},
methods: {
updateUser() {
//axios.post('/updateUser', this.user).then(() => { });
},
changedContinent(newContinent) {
// Do something with the new selected continent like changing background relative to the selected continent
console.log('changedContinent: ' + newContinent);
}
}
}
</script>