父组件无法向子组件传参?

·  阅读 103

下面代码检查了多次都觉得逻辑上不应该出错,

😊预期结果是这样的:当点击按钮变换状态

🤢真实结果却是这样的:点击按钮了,没有变换状态

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="app">
	<alert-box :isError="isError" @myEvent="isError = !isError"><span slot="b">Something had happened.</span></alert-box>
</div>
<script type="text/javascript">
var vm = new Vue({
	el : "#app",
	data : {
		isError: 'true',
	},
	methods:{
		clicknow : function (e) {
			console.log(e);
		}
	},
	components:{
		'alertBox':{
			props: {
				isError:{
					required:true
				}
			},
			template: `
		      <div>
				  <div :class="isError ? 'demo-alert-box' : 'demo-right-box'">
					<strong v-if="isError">Error!</strong>
					<strong v-else>Ok!</strong>
					<slot name="b"></slot>
				  </div>
				  <p>{{isError}}</p>
				  <button type="button" @click="myEvent">change status</button>
			  </div>
		    `,
			methods:{
				myEvent(){
					this.$emit('myEvent')
				},
			}
		}
	}
});
</script>
<style type="text/css">
	.demo-right-box{
		background-color: #cdf3b4;
		border: solid 1px #9af099;
		padding: 20px 10px;
	}
	.demo-alert-box{
		background-color: #f3beb8;
		border: solid 1px #f09898;
		padding: 20px 10px;
	}
</style>
</body>
</html>

</style>
</body>
</html>
复制代码

🤔为什么拿不到isError的值呢? 其实[Vue tip]已经告诉你解决方法 😁只要把<alert-box :isError="isError" @myEvent="isError = !isError">中的:isError="isError"改成:is-error="isError",把@myEvent="isError = !isError"改成@my-event="isError = !isError",别忘了子组件发送事件的this.$emit('myEvent')也要改成this.$emit('my-event') 代码就能正常运行啦!!!

分类:
前端
标签:
分类:
前端
标签: