您当前的位置: 首页 >  ide

暂无认证

  • 2浏览

    0关注

    92582博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

vue中的provide和inject实现状态管理、传参、通信、组件

发布时间:2021-06-19 18:05:12 ,浏览量:2

目录
  • 1、html 部分
  • 2、JavaScript 部分
  • 3、css 部分
1、html 部分
 <div id="app"> <div class="component_box"> <h1>问卷调查 <template id="MyVoteTemplate"> <div> <h3> <span v-text="title"> template: `
		

支持人数

反对人数 {{nums.oppNum}}

支持率

`, inject: ['nums'], computed: { ratio() { let total = this.nums.supNum + this.nums.oppNum; if (total === 0) { return '0.00%' } return (this.nums.supNum / total * 100).toFixed(2) + '%'; } } }; // 按钮组件 const VoteButton = { template: `
是否
`, // 和 props 一样都会把注册的信息挂载到实例上 inject: ['change'], methods: { handle(i) { this.change(i); } } }; // provide / inject Vue.component('VotePlugin', { template: '#VotePluginTemplate', props: ['title'], // 这些数据存储在 this._provided 中 // provide: { // supNum: 0, // oppNum: 0, // change: this.change // }, // 可以写成对象,也可以写成闭包的方式 // 必报的方式会在实例上的信息都挂载完成后再处理 // 可以使用 created 声明周期函数验证 provide() { return { // supNum: 0, // oppNum: 0, nums: this.nums, change: this.change } }, components: { VoteContent, VoteButton }, data() { return { nums: { supNum: 0, oppNum: 0 } }; }, methods: { change(i) { i == 'yes' ? this.nums.supNum++ : this.nums.oppNum++; // i == 'yes' ? this._provided.supNum++ : this._provided.oppNum++; // // 强制刷新 // this.$forceUpdate(); } } }); // 父组件 const MyVote = { template: '#MyVoteTemplate', props: { title: { type: [String, Number], // 设置默认值 default: '这是标题' } }, components: { VoteContent, VoteButton } }; // 页面 new Vue({ el: "#app", components: { MyVote }, data: { voteList: [ { id: 1, title: "**是否很漂亮!" }, { id: 2, 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; } 
关注
打赏
1653961664
查看更多评论
立即登录/注册

微信扫码登录

0.3727s