ref和 props

【一】ref

【1】 AboutView.vue

<template>
  <div class="about">
    <h1 ref="h1">This is an about page</h1>
    <Child ref="child"></Child>
    <button @click="handleShow">点我看控制台</button>
  </div>
</template>


<script>
import Child from "@/components/Child.vue";
export  default {
  name:'About',
  data(){
    return {
      name:'xxx'
    }
  },
  methods:{
    handleShow(){
      console.log(this.$refs)
    }
  },
  components:{
    Child
  }
}
</script>

【二】Child.vue

<template>
  <div>
    <div class="top">
      <button>后退</button>
      <span @click="handleShow">{{ title }}</span>
      <button @click="handlelog">前进</button>
    </div>

  </div>

</template>


<script>
export default {
  name: 'Child',
  data() {
    return {
      title: '首页'
    }
  },
  methods: {
    handleShow() {
      alert('1111')
    },
    handlelog(){
      console.log(this.$parent.name)
    }
  }
}

</script>


<style scoped>
.top {
  display: flex;
  justify-content: space-between;
}
</style>

【二】props

功能:让组件接收外部传过来的数据

传递数据:

接收数据:

第一种方式(只接收):

props:['myname'],

第二种方式(限制类型):

props:{name:String}

第三种方式(限制类型、限制必要性、指定默认值):

props:{
	name:{
	type:String, //类型
	required:true, //必要性
	default:'老王' //默认值
	}
}
  • HomeView.vue
<template>
  <div class="app">
    <UserInfo
      :username="username"
      :age="age"
      :isSingle="isSingle"
      :car="car"
      :hobby="hobby"
    ></UserInfo>
  </div>
</template>

<script>
import UserInfo from './components/UserInfo.vue'
export default {
  data() {
    return {
      username: '小帅',
      age: 28,
      isSingle: true,
      car: {
        brand: '宝马',
      },
      hobby: ['篮球', '足球', '羽毛球'],
    }
  },
  components: {
    UserInfo,
  },
}
</script>

<style>
</style>
  • components Userinfo.vue
<template>
  <div class="userinfo">
    <h3>我是个人信息组件</h3>
    <div>姓名:{{username}}</div>
    <div>年龄:{{age}}</div>
    <div>是否单身:{{isSingle}}</div>
    <div>座驾:{{car.brand}}</div>
    <div>兴趣爱好:{{hobby.join('、')}}</div>
  </div>
</template>

<script>
export default {
  props:['username','age','isSingle','car','hobby']
}
</script>

<style>
.userinfo {
  width: 300px;
  border: 3px solid #000;
  padding: 20px;
}
.userinfo > div {
  margin: 20px 10px;
}
</style>
posted @ 2024-05-08 18:39  -半城烟雨  阅读(10)  评论(0)    收藏  举报