学习记录
javascript
onSubmit() {
//提交
//this.$refs.infoForm.validate,这是表单验证
this.$refs.infoForm.validate(valid => {
if (valid) {
console.log(this.infoForm);
var postPara = this.infoForm;
this.$api.post("Blog", postPara, r => {
if (r.success) {
var id = r.response;
this.$notify({
type: "success",
message: "添加成功,感谢技术分享!",
duration: 3000
});
this.$router.replace(`/content/${id}`);
} else {
var errorMsg = r.msg;
this.$message({
type: "error",
message: errorMsg,
showClose: true
});
}
this.list = r.data;
this.page = r.page;
this.TotalCount = r.pageCount;
this.isShow = false;
});
}
});
}
分析:
在这个Vue.js方法中,$
符号 是Vue实例的属性前缀,用于区分Vue内置的实例属性/方法与用户自定义的属性/方法。
具体含义:
1. this.$refs
-
作用 :访问模板中通过
ref
属性注册的DOM元素或组件实例 -
示例 :
this.$refs.infoForm
访问名为 "infoForm" 的表单组件 -
2. this.$api
-
作用:通常是自定义挂载到Vue原型上的API请求方法
-
来源 :在main.js中通过
Vue.prototype.$api = api
添加 -
3. this.$notify
/ this.$message
-
作用:Element UI等UI库提供的通知/消息组件
-
调用方式:通过Vue实例调用
4. this.$router
-
作用:Vue Router的路由实例,用于编程式导航
-
官房文档里是这样说明的:
通过注入路由器,我们可以在任何组件内通过 this.router 访问路由器,也可以通过 this.route 访问当前路由
可以理解为:
this.$router 相当于一个全局的路由器对象,包含了很多属性和对象(比如 history 对象),任何页面都可以调用其 push(), replace(), go() 等方法。
this.$route 表示当前路由对象,每一个路由都会有一个 route 对象,是一个局部的对象,可以获取对应的 name, path, params, query 等属性。
原文链接:https://blog.csdn.net/u014395524/article/details/88194842
为什么使用 $
前缀?
javascript
export default {
data() {
return {
userData: '自定义数据', // 用户自定义数据
$userData: '不推荐' // 避免使用$开头,可能与Vue内置属性冲突
}
},
methods: {
customMethod() {}, // 用户自定义方法
$customMethod() {} // 不推荐
}
}
常见的Vue $
属性:
属性 | 用途 |
---|---|
$refs |
访问模板引用 |
$router |
Vue Router实例 |
$store |
Vuex store实例 |
$emit |
触发自定义事件 |
$on |
监听事件 |
$off |
移除事件监听 |
$nextTick |
DOM更新后执行回调 |
总结 :$
符号是Vue的命名约定,用于标识Vue实例的内置属性和方法,避免与用户自定义的属性名冲突。