gpt4 book ai didi

javascript - vue 组件和 vue 实例之间的通信

转载 作者:行者123 更新时间:2023-11-30 15:42:43 25 4
gpt4 key购买 nike

我刚开始使用 Vue.js,尝试了一段时间后,我不知道如何将某些东西从组件传递到 vue 实例。我将此组件用作评级系统,但我不明白如何将当前值获取到我的主实例( https://fiddle.jshell.net/swyuarc9/ )

Vue.component('star-rating', {

props: {
'name': String,
'value': null,
'id': String,
'disabled': Boolean,
'required': Boolean
},

template: '<div class="star-rating">\
<label class="star-rating__star" v-for="rating in ratings" \
:class="{\'is-selected\': ((value >= rating) && value != null), \'is-disabled\': disabled}" \
v-on:click="set(rating)" v-on:mouseover="star_over(rating)" v-on:mouseout="star_out">\
<input class="star-rating star-rating__checkbox" type="radio" :value="rating" :name="name" \
v-model="value" :disabled="disabled">★</label></div>',

/*
* Initial state of the component's data.
*/
data: function() {
return {
temp_value: null,
ratings: [1, 2, 3, 4, 5]
};
},

methods: {
/*
* Behaviour of the stars on mouseover.
*/
star_over: function(index) {
var self = this;

if (!this.disabled) {
this.temp_value = this.value;
return this.value = index;
}

},

/*
* Behaviour of the stars on mouseout.
*/
star_out: function() {
var self = this;

if (!this.disabled) {
return this.value = this.temp_value;
}
},

/*
* Set the rating of the score
*/
set: function(value) {
var self = this;

if (!this.disabled) {
// Make some call to a Laravel API using Vue.Resource

this.temp_value = value;
return this.value = value;
}
}
}

});

new Vue({
el: '#app'
});

最佳答案

欢迎使用 Vue!

一开始可能有点难,但是您传递属性的方式是通过 props。为此,您需要先在父级(在本例中为您的应用程序实例)上定义一个 data 对象。

vue-docs 中有一些关于 Prop 的好例子.
通常,您可以这样做:

new Vue({
el: '#app',
data: function () {
return {
foo: 'Foo'
}
}
});

Vue.component('bar', {
props: { foo: String },
template: '<span> {{ foo }}</span>'
})

...和 ​​HTML

<div id="app">
<bar :foo="foo"></bar<
</div>

我 fork 了你的 fiddle 并添加了一个演示 Prop ,只是为了让你看到它的实际效果。 Check it out .

关于javascript - vue 组件和 vue 实例之间的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40551149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com