目录
1、html 部分
- 1、html 部分
- 2、JavaScript 部分
- 3、css 部分
<div id="app"> <div class="component_box"> <h1>问卷调查 <template id="MyVoteTemplate"> <div> <h3> <span v-text="title">{num}} <template id="VoteContent"> <div> <p>是 {{supNum}}{oppNum}} <template id="VoteButton"> <div class="btn_box"> <button @click="handle('no')">是 template: '#VoteContent', props: ['eventbus'], data() { return { supNum: 0, oppNum: 0 } }, computed: { ratio() { let total = this.supNum + this.oppNum; if (total === 0) { return '0.00%' } return (this.supNum / total * 100).toFixed(2) + '%'; } }, created() { // 基于 $on 创建一个自定义事件, // 把指定的方法放到任务队列中 this.eventbus.$on('changesupport', this.changeNum); }, methods: { changeNum(type) { type == 'no' ? this.supNum++ : this.oppNum++; } } }; // 按钮组件 const VoteButton = { template: '#VoteButton', props: ['eventbus'], data() { return {} }, methods: { handle(i) { // 通知任务队列中 @changeparent 这个自定事件执行 // 第一个参数是自定义事件类型, // 第二个参数是通知方法执行的时候, // 给方法传递参数 this.$emit('changeparent', i); // 通知 eventBus 任务队列中的 changesupport 自定义事件执行 this.eventbus.$emit('changesupport', i); } } }; // 父组件 const MyVote = { template: '#MyVoteTemplate', // props: ['title'], // props: { // title: String // }, // props: { // title: [String, Number] // }, // props: { // title: { // type: [String, Number], // // true 必须传,false 可不传 // require: true // } // }, props: { title: { type: [String, Number], // 设置默认值 default: '这是标题' } }, // props: { // // title: String // title: { // type: [String, Number], // // 自定义校验规则 // validator(val) { // return val.length >= 3; // } // } // }, components: { VoteContent, VoteButton }, data() { return { num: 0, eventBus: new Vue } }, methods: { changeParent(type) { this.num += 1; } } }; // 页面 new Vue({ el: "#app", components: { MyVote }, data: { voteList: [ { id: 1, title: "**是否很漂亮!" }, { id: 2, title: "***是否很帅!" }, // { // id: 3, // title: "**是否很耐看!" // } ], } });3、css 部分
.component_box { position: fixed; left: 50%; top: 50%; transform: translate(-50%, -50%); } .commponents { border-bottom: 1px solid #666666; padding: 20px 0; box-sizing: border-box; } .btn_box>button:first-child { color: blue; } .btn_box>button:last-child { margin-left: 16px; }