[英]How to pass Boolean props to another component in vuejs
I have two components: component A and Component B. In the component A, I have a props called hasBorder
with Boolean type and when i call component A in the component B, I passed value to a props component of component A, I have an error.我有两个组件:组件 A 和组件 B。在组件 A 中,我有一个名为
hasBorder
的布尔类型的道具,当我在组件 B 中调用组件 A 时,我将值传递给组件 A 的道具组件,我有一个错误。
html component A: html组件A:
<div> <img src="path" :style="hasBorder ? 'border:5px;': ''"/></div>
js component A: js组件A:
Vue.component('compA', {
props: {
hasBorder:{
type:Boolean,
default:false
}
}
});
html component B: html组件B:
<div> My image : <compA has-border="myStyle"></compA></div>
js component B: js组件B:
Vue.component('compB', {
data: {
return {
myStyle : { type:Boolean, default :true}
}
}
});
I have this error "Invalid prop:type check failed for prop hasBorder
. Expected Boolean, got String with value "myStyle".我有这个错误“无效的道具:道具
hasBorder
的类型检查失败。预期的布尔值,得到值为“myStyle”的字符串。
How can i fix this error please请问我该如何解决这个错误
You expect bool value but you are trying to send an object.您期望 bool 值,但您正在尝试发送一个对象。
Try this尝试这个
Vue.component('compB', { data: { return { myStyle : true } } });
And use v-bind并使用 v-bind
<div> My image : <compA v-bind:has-border="myStyle"></compA></div>
You need to bind your props with v-bind:
or :
in order to pass data.您需要使用
v-bind:
或:
绑定您的道具以传递数据。 Data property needs to be a function that returns object.数据属性需要是一个返回对象的函数。 Please take a look at snippet:
请看一下片段:
const app = Vue.createApp({ data() { return { myStyle: true, myPath: 'https://picsum.photos/100' }; }, }) app.component('compA', { template: ` <div><img :src="path" :style="hasBorder ? 'border: 5px solid turquoise;': ''"/></div> `, props: { hasBorder:{ type:Boolean, default:false }, path: { type: String, default: '' } } }) app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script> <div id="demo"> <div> My image : <comp-a :has-border="myStyle" :path="myPath"></comp-a></div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.