Vue.js 基础
Vue.js个人整理
基础篇
声明式渲染
<div id="sdq"> Counter: {{ counter }} </div> <script> const Counter = { data() { return { counter: 0 } }, mounted() { setInterval(() => { this.counter++ }, 1000) } } Vue.createApp(Counter).mount('#sdq') </script>
|
v-bind:title
v-bind attribute 被称为指令指令带有前缀 v-, 以表示它们是 Vue 提供的特殊 attribute可能你已经猜到了, 它们会在渲染的 DOM 上应用特殊的响应式行为在这里, 该指令的意思是: 将这个元素节点的 title attribute 和当前活跃实例的 message property 保持一致
<div id="bind-attribute"> <span v-bind:title="message"> 鼠标悬停几秒钟查看此处动态绑定的提示信息 </span> </div> <script> const AttributeBinding = { data() { return { message: '我叫史迪奇 ' + new Date().toLocaleString() } } } Vue.createApp(AttributeBinding).mount('#bind-attribute') </script>
|
处理用户输入
<div id="fangzhuang"> <p>{{ message }}</p> <button v-on:click="reverseMessage">反转 Message</button> </div> <script> const EventHandling = { data() { return { message: '我叫史迪奇' } }, methods: { reverseMessage() { this.message = this.message .split('') .reverse() .join('') } } } Vue.createApp(EventHandling).mount('#fangzhuang') </script>
|
条件与循环
条件
<body> <div id="conditional-rendering"> <span v-if="seen">现在你看到我了</span> </div> <script> const ConditionalRendering = { data() { return { seen: true } } }
Vue.createApp(ConditionalRendering).mount('#conditional-rendering') </script> </body>
|
循环
<div id="list-rendering"> <ol> <li v-for="todo in todos"> {{ todo.text }} </li> </ol> </div> <script> const ListRendering = { data() { return { todos: [ { text: '史迪奇' }, { text: '鲁本' }, { text: '安琪' } ] } } }
Vue.createApp(ListRendering).mount('#list-rendering') </script>
|
组件化应用构建
<ol> <todo-item></todo-item> </ol> <script> const app = Vue.createApp()
app.component('todo-item', { template: `<li>This is a todo</li>` })
app.mount() </script>
|
综合案例
<div id="components-app" class="demo"> <ol> <todo-item v-for="item in groceryList" v-bind:todo="item" v-bind:key="item.id" ></todo-item> </ol> </div> <script> const ComponentsApp = { data() { return { groceryList: [ { id: 0, text: '史迪奇' }, { id: 1, text: '鲁本' }, { id: 2, text: '安琪' } ] } } }
const app = Vue.createApp(ComponentsApp)
app.component('todo-item', { props: ['todo'], template: `<li>{{ todo.text }}</li>` })
app.mount('#components-app') </script>
|
作者: 我叫史迪奇
本文来自于:
https://sdq3.link/Vue-Basics.html博客内容遵循 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议