Answer the question
In order to leave comments, you need to log in
How to make a component with parameters?
Hey! I am new to vue. Faced a problem, most likely elementary. But I can't find a solution.
I'm trying to make a component library using vue cli.
Made a simple "list" component:
App.vue
<template>
<div id="app">
<OptionsList v-bind:options="options" />
</div>
</template>
<script>
import OptionsList from './components/OptionsList.vue'
export default {
name: 'app',
components: {
OptionsList
},
data: function() {
return {
options: [{id:0, value: 'first'},
{id:1, value: 'second'}
]
}
}
}</script>
<template>
<div>
<ul>
<OptionsItem
v-for="(item, index) in options"
v-bind:idx="index"
v-bind:key="index"
v-bind:errors="errors"
v-bind:len="optionsCount"
v-bind:option="item"
v-bind:readOnly="readOnly"
v-on:del-click="delClick($event)"
v-on:sort-click="sortClick($event)"/>
</ul>
<button v-on:click.prevent="addClick">Добавить</button></div>
</template>
<script>
import OptionsItem from './OptionsItem.vue'
export default {
name: 'OptionsList',
components: {
OptionsItem
},
props: {
options: Array,
readOnly: Boolean
},
data: function() {
return {
errors: []
}
},
computed: {
optionsCount: function() {
return this.options.length;
}
},
methods: {
addClick: function () {
window.console.log('add click');
this.options.push({ id: this.options.length, value: null });
},
delClick: function (idx) {
window.console.log('del click' + idx);
this.options.splice(idx, 1);
this.options.forEach((item, idx) => { item.id = idx; });
},
sortClick: function (param) {
if (param.dir === 1) {
this.options[param.idx].id--;
this.options[param.idx - 1].id++;
} else {
this.options[param.idx].id++;
this.options[param.idx + 1].id--;
}
this.options.sort(function(a, b) {
return b.id > a.id ? -1 : 1;
});
}
}
}
</script>
<template>
<li>
<span>{{idx + 1}}</span>
<input type="text" v-bind:readOnly="readOnly" v-bind:class="{error: errors.find(e=>{return e.field=='option_'+idx;})}" v-model="option.value">
<button v-if="!readOnly" v-on:click.prevent="$emit('del-click', idx)">Удалить</button>
<button v-if="!readOnly && idx > 0" v-on:click.prevent="$emit('sort-click', {idx: idx, dir: 1})">↑</button>
<button v-if="!readOnly && idx < len - 1" v-on:click.prevent="$emit('sort-click', {idx: idx, dir: 0})">↓</button>
</li>
</template>
<script>
export default {
name: 'OptionsItem',
props: {
option: Object,
idx: Number,
len: Number,
errors: Array,
readOnly: Boolean
}
}
</script>
<div id="app">
<demo></demo>
</div>
<script>
new Vue({
components: {
demo: OptionsForm
}
}).$mount('#app');
</script>
<script>
new Vue({
components: {
demo: OptionsForm
}
}).$mount('#app');
OptionsForm.options = [{id:0, value: 'first'}, {id:1, value: 'second'}];
</script>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question