VUE3.0,DAY44
回归一下脚手架的使用
我们创建了一个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