我试图让我的按钮(在vue组件内部)在按下时显示警告,并且消息是输入字段内容。
到目前为止,我有以下内容:
HTML
<vue-form-input placeholder="Name"></vue-form-input>
<vue-form-submit button-text="Submit"></vue-form-submit>
JS
Vue.component('vue-form-input', {
props: {
placeholder: {
String,
required: true
}
},
template:`
<div>
<input type="text" class="form-control" :placeholder="placeholder">
</div>` });
Vue.component('vue-form-submit', {
props: {
buttonText: {
String,
required: true,
default: 'Submit' }
},
template:`
<div>
<button v-on:click="submitBut" class="btn btn-lg btn-primary btn-block" type="submit">{{buttonText}}</button>
</div>` });
new Vue({
el: '#forms',
data: {
},
methods: {
submitBut: () => {
alert('Blablabla')
}
}, })
存在控制台错误 1)财产或方法&#34; submitBut&#34;未在实例上定义,但在呈现期间引用。确保在数据选项中声明反应数据属性。 2)事件的处理程序无效&#34;点击&#34;:未定义
有人可以帮助我吗?
答案 0 :(得分:1)
从孩子到父母(see this post to understand)发出:
Vue.component('vue-form-input', {
props: {
initName: { type: String },
placeholder: {
type: String,
required: true
}
},
data: function() {
return {
name: this.initName
}
},
template:`
<div>
<input v-model="name" type="text" class="form-control" :placeholder="placeholder">
</div>`,
watch: {
name: function() {
this.$emit('change', this.name);
}
}
});
Vue.component('vue-form-submit', {
props: {
buttonText: {
String,
required: true,
default: 'Submit' }
},
template:`
<div>
<button v-on:click="submitBut" class="btn btn-lg btn-primary btn-block" type="submit">{{buttonText}}</button>
</div>`,
methods: {
submitBut: function() {
this.$emit('submit');
}
}
});
new Vue({
el: '#forms',
data: {
name: ''
},
methods: {
changeInput: function(name) {
this.name = name;
},
submitBut: function() {
alert(this.name);
}
}
})
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.5/vue.js"></script>
<div id="forms">
<vue-form-input @change="changeInput" :init-name="name" placeholder="Name"></vue-form-input>
<vue-form-submit @submit="submitBut" button-text="Submit"></vue-form-submit>
Parent : {{ name }}
</div>
&#13;