VUE3.0,DAY44,vue中的ref属性

回归一下脚手架的使用

我们创建了一个vue脚手架,然后删除掉里边的src文件夹,然后我们在同目录下自己重新建立一个src文件夹,然后新建一个components文件夹,新建App.vue,新建main.js,在components文件夹内新建一个自己的组件School.vue。其他的文件不要动。在这里插入图片描述
随后我们自己编写新建文件的代码。
首先是mainjs中的

// 引入vue
import Vue from "vue";
//引入app
import App from './App.vue'
//关闭vue的生成提示
Vue.config.productionTip = false
//创建vm
new Vue({
    el: "#app",
    render:h=>h(App)
})

然后是新建的组件school.vue中的


<template>
  <div class="school">
    <h2>学校的名称:{{ name }}</h2>
    <h2>学校的地址:{{ address }}</h2>
  </div>
</template>

<script>
export default {
  School: "School",
  data() {
    return {
      name: "尚硅谷",
      address: "哈哈",
    };
  },
};
</script>

<style>
.school {
  background-color: chartreuse;
}
</style>

然后是App.vue中的

<template>
  <div>
    <School></School>
  </div>
</template>

<script>
//引入School组件
import School from "./components/School.vue";
//注册组件
export default {
  name: "App",
  components: { School },
};
</script>

<style>
</style>

然后在vs code打开终端输入npm run serve 。发现成功运行。在这里插入图片描述

增加新需求使用ref实现

我们在上边的案例中增加新的需求,增加一段话,然后增加一个按钮,点击按钮,就会把增加的那一段话输出为DOM元素。修改App.vue的代码如下。然后点击按钮,发现控制台输出了h1标签中的话。

<template>
  <div>
    <School></School>
    <h1 v-text="msg" ref="title"></h1>
    <button @click="showDom">点我输出上方的DOM元素</button>
  </div>
</template>

<script>
//引入School组件
import School from "./components/School.vue";
//注册组件
export default {
  name: "App",
  data() {
    return {
      msg: "欢迎学习vue",
    };
  },
  components: { School },
  methods: {
    showDom() {
      //console.log(this);这里会输出vueComponents的一些东西
      console.log(this.$refs.title);
    },
  },
};
</script>

<style>
</style>

在这里插入图片描述
在这里插入图片描述

总结

ref属性:
1.被用来给元素或子组件注册引用信息(id的替代者)
2.应用在html标签上获取的是真实DOM元素,应用在组件标签上是组件实例对象(vc)
3.使用方式:
打标识: <h1 ref="xx">.....</h1> 或<School ref=" xxx" ></School>
获取: this. $refs .xxx

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值