vue的声明式渲染,属性绑定,事件监听,表单绑定,条件渲染,列表呈现,计算属性0,vue观察者的代码
时间: 2023-07-18 20:25:33 浏览: 85
vue计算属性computed、事件、监听器watch的使用讲解
5星 · 资源好评率100%
声明式渲染:
```html
<div id="app">
<p>{{ message }}</p>
</div>
```
```javascript
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
})
```
属性绑定:
```html
<div id="app">
<img v-bind:src="imageSource" alt="image">
</div>
```
```javascript
var app = new Vue({
el: '#app',
data: {
imageSource: 'path/to/image.jpg'
}
})
```
事件监听:
```html
<div id="app">
<button v-on:click="incrementCounter">Click me!</button>
<p>Counter: {{ counter }}</p>
</div>
```
```javascript
var app = new Vue({
el: '#app',
data: {
counter: 0
},
methods: {
incrementCounter: function () {
this.counter++;
}
}
})
```
表单绑定:
```html
<div id="app">
<input v-model="message" type="text">
<p>{{ message }}</p>
</div>
```
```javascript
var app = new Vue({
el: '#app',
data: {
message: ''
}
})
```
条件渲染:
```html
<div id="app">
<p v-if="showMessage">{{ message }}</p>
<button v-on:click="toggleMessage">Toggle message</button>
</div>
```
```javascript
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!',
showMessage: true
},
methods: {
toggleMessage: function () {
this.showMessage = !this.showMessage;
}
}
})
```
列表呈现:
```html
<div id="app">
<ul>
<li v-for="item in items">{{ item }}</li>
</ul>
</div>
```
```javascript
var app = new Vue({
el: '#app',
data: {
items: ['item1', 'item2', 'item3']
}
})
```
计算属性:
```html
<div id="app">
<p>Length: {{ messageLength }}</p>
<input v-model="message" type="text">
</div>
```
```javascript
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
},
computed: {
messageLength: function () {
return this.message.length;
}
}
})
```
Vue 观察者:
```javascript
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
},
watch: {
message: function (newValue, oldValue) {
console.log('New message: ' + newValue);
console.log('Old message: ' + oldValue);
}
}
})
```
阅读全文