案例思路:
- html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>title>
- <script src="../js/vue.js">script>
- <script src="../components/step.js">script>
- head>
- <body>
- <div id="app">
-
- <h1>组件传参h1>
- <p>父传子p>
-
- <step :value="r" @input="r=$event" :min="100" :max="500" :step="10">step><br>
- <input type="range" :min="100" :max="500" v-model.number="r">
- <div :style="{'border':'2px solid red',borderRadius:r+'px',height:r+'px',width:r+'px'}">div>
- div>
- <script>
- new Vue({
- el:"#app",
- // 02注册组件
- components:{step},
- data(){
- return{
- r:100,
- }
- }
- })
- script>
- body>
- html>
- // 01定义组件
- var step = {
- template: `
-
-
-
- `,
- props: { //props接受父组件传递过来的参数 父传子
- value: { //参数名称value
- type: Number,
- default: 1 //默认值是1 如果不传value的值是1
- },
- min: {
- type: Number,
- default: 1
- },
- max: {
- type: Number,
- default: 999
- },
- step: {
- type: Number,
- default: 1
- }
- },
- data() {
- return {
- count: this.value //count的默认值是父组件传过来的参数value
- }
- },
- watch: {
- count: {
- handler() {
- // 限定最大值 最小值
- if (this.count >= this.max) {
- this.count = this.max
- };
- if (this.count <= this.min) {
- this.count = this.min
- };
- //子传父 通过emit发送事件
- this.$emit("input", this.count);
-
- },
- deep: true,
- },
- value: {
- handler() {
- this.count = this.value;
- },
- deep: true
- }
- }
-
- }
- //为什么不直接使用this.value和input框绑定
- // 因为 父组件传到子组件的参数必须是只读
- // 当count的数据局发生变化时通知父组件更新数据