创建和连接Vue应用程序实例
初始代码
- HTML的初始代码非常的检测,几个标题就结束了
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vue Basics</title>
<link
href="https://fonts.googleapis.com/css2?family=Jost:wght@400;700&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="styles.css" />
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="app.js" defer></script>
</head>
<body>
<header>
<h1>Vue Course Goals</h1>
</header>
<section id="user-goal">
<h2>My Course Goal</h2>
<p></p>
</section>
</body>
</html>
- CSS代码的话自己看一下,难度也不是很大
* {
box-sizing: border-box;
}
html {
font-family: 'Jost', sans-serif;
}
body {
margin: 0;
}
header {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.26);
margin: 3rem auto;
border-radius: 10px;
padding: 1rem;
background-color: #4fc08d;
color: white;
text-align: center;
width: 90%;
max-width: 40rem;
}
#user-goal {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.26);
margin: 3rem auto;
border-radius: 10px;
padding: 1rem;
text-align: center;
width: 90%;
max-width: 40rem;
}
#user-goal h2 {
font-size: 2rem;
border-bottom: 4px solid #ccc;
color: #4fc08d;
margin: 0 0 1rem 0;
}
#user-goal p {
font-size: 1.25rem;
font-weight: bold;
border: 1px solid #4fc08d;
background-color: #4fc08d;
color: white;
padding: 0.5rem;
border-radius: 25px;
}
#user-goal input {
font: inherit;
border: 1px solid #ccc;
}
#user-goal input:focus {
outline: none;
border-color: #1b995e;
background-color: #d7fdeb;
}
#user-goal button {
font: inherit;
cursor: pointer;
border: 1px solid #ff0077;
background-color: #ff0077;
color: white;
padding: 0.05rem 1rem;
box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.26);
}
#user-goal button:hover,
#user-goal button:active {
background-color: #ec3169;
border-color: #ec3169;
box-shadow: 1px 1px 4px rgba(0, 0, 0, 0.26);
}
- 当然JS肯定是空的,需要我们自己去添写,这个demo非常简单,就是使用Vue来控制我们的P标签,来做相应的输出
const app = Vue.createApp();
app.mount('#user-goal');
首先我们创建要给新的应用实例
- 应用实例的理解
每个 Vue 应用都是通过
createApp
函数创建一个新的 应用实例,应用实例必须在调用了.mount()
方法后才会渲染出来。该方法接收一个“容器”参数,可以是一个实际的 DOM 元素或是一个 CSS 选择器字符串
- 之后在实例中有一个固定的写法
const app = Vue.createApp({
data() {
return {
courseGoal: '学习Vue,完成这个框架'
};
}
});
app.mount('#user-goal');
在官方的解释中,data用于声明组件初始响应式状态的函数。
插值和数据绑定
- 现在我们已经在data里面声明了响应式状态的数据,我们也知道我们需要在P标签的地方来进行显示,那我们在P标签中如何插入这些动态数据呢,这时候就需要使用插值来绑定我们的动态数据
<p>{{ courseGoal }}</p>
- 并且当我们修改data的这个数据时候,页面也会即时的发生变化
const app = Vue.createApp({
data() {
return {
courseGoal: 'IT知识一享!!!'
};
}
});
app.mount('#user-goal');
双大括号标签会被替换为相应组件实例中
msg
属性的值。同时每次msg
属性更改时它也会同步更新。