慈溪市建设厅网站,网站关键字分析,快手淘客网站是怎么做的,电商网站制作方案目录
template 属性
data 属性
methods 属性
疑问
function 函数的两种写法
methods 属性中 this 的指向
总结 Vue 实例是通过 Vue.createApp() 创建的#xff0c;该函数需要接收一个对象作为参数#xff0c;该对象可添加 template、data、methods 等属性。 template …目录
template 属性
data 属性
methods 属性
疑问
function 函数的两种写法
methods 属性中 this 的指向
总结 Vue 实例是通过 Vue.createApp() 创建的该函数需要接收一个对象作为参数该对象可添加 template、data、methods 等属性。 template 属性 vue.js 3 中的 template 属性用于定义需要渲染的模板内容其中包括 html 标签或组件最终将其挂载到 元素上相当于为 innerHTML 赋值。
在模板中会使用一些语法例如 {{}} 和 click 等。 data 属性
data 属性用于为 vue.js 组件定义响应式数据该属性需要传入一个函数该函数返回一个对象。
该对象会被 vue.js 劫持之后对该对象的修改或访问都会在劫持中被处理所以该对象中定义的数据都是响应式的。
例如在 template 中通过使用 {{counter}}可访问到该对象定义的 counter当修改 counter 时template 中的 {{counter}} 也会发生改变。
在浏览器中运行代码时需要注意。
在 vue.js 2 中data 属性可传入一个对象。
在 vue.js 3 中data 属性必须传入一个函数否则会在浏览器中报错。 methods 属性
methods 属性需要传入一个对象通常会在这个对象中定义很多方法可以被绑定到模板中在该方法中可以使用 this 直接访问 data 返回对象的属性。
methods 中定义的方法不能使用箭头函数。 疑问
为什么 methods 属性中定义的方法不能使用箭头函数 https://v2.cn.vuejs.org/v2/api/#methods https://cn.vuejs.org/api/options-state.html#methods function 函数的两种写法
// function 函数的简写语法
decrement() {this.counter--;console.log(decrement, this)
},
// function 函数的完整语法
decrement:function() {this.counter--;
} 可知简写是在完整的基础上少了 :function !DOCTYPE html
html langen
headmeta charsetUTF-8meta nameviewport contentwidthdevice-width, initial-scale1.0titleDocument/title
/head
bodydiv idapp/div!-- 用 template 标签编写模板内容需要添加 id 属性 --template idwhydivh2{{message}}/h2h2{{counter}}/h2button clickincrement1/buttonbutton clickdecrement-1/button/div/templatescript src./js/vue.js/scriptscriptVue.createApp({template: #why, // 通过id选择器选中 template idwhy/template 模板data: function() {return {message: methods中的this,counter: 100}},methods: {// 1.箭头函数increment:() {this.counter;console.log(increment, this)},// 2.function 函数的简写语法decrement() {this.counter--;console.log(decrement, this)},// 3.function 函数的完整语法// decrement:function() {// this.counter--;// }}}).mount(#app);/script
/body
/html
在浏览器中运行代码f12 打开控制台先点击 -1 按钮再点击 1 按钮控制台输出如下 箭头函数中的 this 会指向 Window这里涉及箭头函数使用 this 的查找规则它会在自己上层作用域中查找 this。这里找到的刚好是 script 作用域中的 this所以就是 Window。
就是 vue.js 在执行过程中创建了一个 Proxy 对象通过代理对象来处理数据不是js原生的 Window 对象。 methods 属性中 this 的指向
在 vue.js 3源码中所在在 methods 中定义的方法都会被遍历通过 bind 函数绑定 this确保方法中的 this 指向 vue 实例的代理对象。 https://github.com/vuejs/core/blob/v3.2.23/packages/runtime-core/src/componentOptions.ts#L633 通过 bind() 为每个函数绑定了 publicThis即 vue 实例的代理对象。 https://github.com/vuejs/core/blob/v3.2.23/packages/runtime-core/src/componentOptions.ts#L544 除了 methods 中的 this 指向 vue 实例的代理对象data、computed、watch 等也都绑定了同一个 this。 Vue.createApp() 的对象除了可以编写 template、data、methods 属性还可以定义其他属性比如 props、computed、watch、emits、setup 和生命周期函数等。 总结
Vue.createApp的对象参数
属性名作用注意事项template定义需要渲染的模板内容data为 vue.js 组件定义响应式数据该属性需要传入一个函数该函数返回一个对象methods需要传入一个对象通常会在这个对象中定义很多方法可以被绑定到模板中在该方法中可以使用 this 直接访问 data 返回对象的属性。methods 中定义的方法不能使用箭头函数。