vue filters和directives访问this的问题详解

目录
  • vue filters和directives访问this
  • directives所遇小bug

vue filters和directives访问this

记录一次奇葩的需求。

要求自定义一个指令,点击后能跳转指定路由。

directives和filters压根就没法访问this。

脑袋都想破了。

不废话了,上代码。

<template>
    <div>
        <div v-join="(divData, that)">tag标签</div>
        <p>{{divData}}</p>
        <p>{{divData | sum(that)}}</p>
    </div>
</template>
<script>
export default {
    name: 'Main',
    data(){
        return {
            divData:'传入的值',
            that: this,
            filtersData: '过滤器的值'
        }
    },
    filters: {
        sum(val, that){
            return `${val}和${that.filtersData}`
        }
    },
    directives: {
        join: {
            inserted(el, binding){

            },
            bind(el, binding){
                console.log('------2')
                el.addEventListener('click', function(){
                    binding.value.that.$router.push({
                        path: '/aside'
                    })

                })
            }
        }
    }
}
</script>

解决方案是在data中定义一个that变量指向this,再将这个变量当做参数传进directives,在directives内部就可以访问到this了,filters同理。

directives所遇小bug

自己在利用vue写todoList的时候遇到一个小bug,记录一下

写个指令,当双击进行编辑todo,让其自动聚焦,结果效果如下,

代码如下:

directives: {
    focus(el,bindings) {
        if(bindings.value) {
              el.focus();
         }
     }
}
<input v-focus="todo == t" type="text" v-show="todo == t"  v-model="todo.title" @blur="reset" @keyup.13="reset" >

多方查找原因,把自定义v-focus指令放末尾,就好了,代码如下:

<input type="text" v-show="todo == t"  v-model="todo.title" @blur="reset" @keyup.13="reset" v-focus="todo == t">

是否自定义指令都应放后面呢?这就需要以后验证了

完整代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
    <style>
        .del{
            text-decoration: line-through;
            color: #ccc!important;
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <div class="panel panel-warning">
                        <div class="panel-heading">
                            <input type="text" v-model="value" class="form-control" @keydown.enter="add">
                        </div>
                        <div class="panel-body">
                            <ul class="list-group">
                                <li class="list-group-item" @dblclick="change(todo)" v-for="(todo,index) in todos" :key="index">
                                    <div v-show="todo != t" :class="{del: todo.isSelected}">
                                        <input type="checkbox" v-model="todo.isSelected">{{todo.title}}
                                        <button class="pull-right btn btn-danger btn-xs" @click="remove(index)">&bigotimes;</button>
                                    </div>
                                    <input type="text" v-show="todo == t"  v-model="todo.title" @blur="reset" @keyup.13="reset" v-focus="todo == t">
                                    <!-- 下面是错误代码,可以把上面的注释掉打开下面的对比下 -->
                                    <!-- <input v-focus="todo == t" type="text" v-show="todo == t"  v-model="todo.title" @blur="reset" @keyup.13="reset" > -->
                                </li>
                            </ul>
                        </div>
                        <div class="panel-footer">
                            <ul class="nav nav-pills">
                                <li role="presentation" class="active"><a href="#">全部</a></li>
                                <li role="presentation"><a href="#">已完成</a></li>
                                <li role="presentation"><a href="#">未完成</a></li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="../node_modules/vue/dist/vue.js"></script>
    <script>
        let vm = new Vue({
            el:'#app',
            data:{
                todos:[],
                hash:'complete',//路径切换时 获取的hash值
                value:'',// 输入框中需要增加的内容,
                t:''//当前点击的那一个
            },
            created(){ //当vue创建时执行的方法
                //如果storage有 就用这里的值 没有就是空数组
                this.todos = JSON.parse(localStorage.getItem('todos')) || [{isSelected:true,title:'晚上回去睡觉'}];
            },
            watch:{  //watch默认 只监控一层,例如 todos 可以监控数组的变化,监控不到对象的变化
                todos:{
                    handler(){
                        localStorage.setItem('todos',JSON.stringify(this.todos));
                    },
                    deep:true
                }
            },
            methods:{
                addTodo(){
                    let todo = {isSelected:false,title:this.value};
                    this.todos.push(todo);
                    this.value = '';
                },
                remove(todo){
                    this.todos = this.todos.filter(item=>todo!==item);
                },
                change(todo){
                    //todo代表的是我当前点击的是哪一个,存储当前点击的这一项
                    this.t = todo;
                },
                reset(){
                    this.t = '';
                }
            },
            computed:{
                lists(){
                    if(this.hash === 'complete'){
                        return this.todos;
                    }
                    if(this.hash === 'finish'){
                        return this.todos.filter(item=>item.isSelected)
                    }
                    if(this.hash === 'unfinish'){
                        return this.todos.filter(item=>!item.isSelected)
                    }
                },
                total(){
                    //求出数组中为false的个数
                    //将数组中的true全部干掉,求出剩余length
                    return this.todos.filter(item=>!item.isSelected).length;
                }
            },
            directives:{ //指令,就是操作dom
                focus(el,bindings){
                    //bindings中有一个value属性 代表的是指令对应的值v-auto-focus="值"
                    if(bindings.value){
                        el.focus();
                    }
                    //console.log(el,bindings);
                }
            }
        });
        let listener = () => {
            let hash = window.location.hash.slice(1) || 'complete'; //如果打开页面没有hash默认是全部
            vm.hash = hash;
        };
        listener(); //页面一加载 就需要获取一次hash值,否则可能导致 回到默认hash
        window.addEventListener('hashchange',listener,false);
    </script>
</body>
</html>

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • 过滤器vue.filters的使用方法实现

    写项目的时候,有一些方法我们是需要全局使用的,比如数字的四色五入保留小数点啊.一些工具方法.字符的格式化啊等等.这些很多页面需要用的.使用频率极高的方法,我们一般会将其封装为全局的方法:我以前是这样做的,有这么几种方式: 1.挂载到vue.prototype 在main.js入口文件中挂载到vue.prototype,如我们封装一个获取时间戳的函数. Vue.prototype.now = Date.now || function () { return new Date().getTime()

  • Vue 过滤器filters及基本用法

    1.示例代码 采用vue单文件组件,使用moment插件格式化日期 <template> <div> <h1>{{date | dateFormat}}</h1> </div> </template> <script> import moment from 'moment'; import 'moment/locale/zh-cn'; moment.locale('zh-cn'); export default { dat

  • 详解Vue中的filter与directive

    目录 vue自定义指令--directive 全局指令 局部指令 使用 钩子函数(均为可选) 使用及参数 vue中的过滤器分为两种:局部过滤器和全局过滤器 过滤器可被用于一些常见的文本格式化.过滤器可以用在两个地方:双花括号插值和 v-bind 表达式 (后者从 2.1.0+ 开始支持).过滤器应该被添加在 JavaScript 表达式的尾部,由"管道"符号指示(官方文档) <!-- 在双花括号中 --> {{ message | capitalize }} <!--

  • vue filters和directives访问this的问题详解

    目录 vue filters和directives访问this directives所遇小bug vue filters和directives访问this 记录一次奇葩的需求. 要求自定义一个指令,点击后能跳转指定路由. directives和filters压根就没法访问this. 脑袋都想破了. 不废话了,上代码. <template> <div> <div v-join="(divData, that)">tag标签</div> &l

  • vue从使用到源码实现教程详解

    搭建环境 项目github地址 项目中涉及了json-server模拟get请求,用了vue-router: 关于Vue生命周期以及vue-router钩子函数详解 生命周期 1.0版本 1.哪些生命周期接口 init Created beforeCompile Compiled Ready Attatched Detached beforeDestory destoryed 2.执行顺序 1. 不具有keep-alive 进入: init->create->beforeCompile->

  • Vue中mixins混入的介绍与使用详解

    目录 一.来自官网的描述 二.如何创建Mixins 三.项目中如何使用混入 四.与vuex的区别 五.与公共组件的区别 一.来自官网的描述 混入 (mixins): 是一种分发 Vue 组件中可复用功能的非常灵活的方式.混入对象可以包含任意组件选项.当组件使用混入对象时,所有混入对象的选项将被混入该组件本身的选项. 二.如何创建Mixins 在src目录下创建一个mixins文件夹,文件夹下新建一个myMixins.js文件.前面我们说了mixins是一个js对象,所以应该以对象的形式来定义my

  • 对Vue.js之事件的绑定(v-on: 或者 @ )详解

    1.Vue.js事件绑定的一般格式 v-on:click='function' v-on:click/mouseout/mouseover/ @click 2.Vue.js事件绑定的实现 2.1 JavaScript代码 <script type="text/javascript" src="../js/vue-1.0.21.js"></script> <script type="text/javascript"&g

  • vue项目前端错误收集之sentry教程详解

    sentry简介 Sentry 是一个开源的错误追踪工具,可以帮助开发人员实时监控和修复系统中的错误.其专注于错误监控以及提取一切事后处理所需的信息;支持几乎所有主流开发语言( JS/Java/Python/php )和平台, 并提供了web来展示输出错误. sentry官网: https://sentry.io/ sentry安装 sentry 是一个开源的工具,可以自行搭建. 官方支持两种安装和运行 Sentry 服务器的方法, Docker 和 Python .推荐使用 Docker .

  • vue实现绑定事件的方法实例代码详解

    一.前言 vuejs中的事件绑定,使用<v-on:事件名 = 函数名>来完成的,这里函数名是定义在Vue实例中的methods对象中的,Vue实例可以直接访问其中的方法. 二.事件绑定方式 1. 直接在标签中写js方法  <button v-on:click="alert('hi')">执行方法的第一种写法</button> 2.调用method的办法 <button v-on:click="run()">执行方法的第

  • vue中使用mxgraph的方法实例代码详解

    1.npm 引入 npm install mxgraph --save 2.这个模块可以使用require()方法进行加载.它将返回一个接受对象作为选项的工厂函数.必须将mxBasePath选项提供给工厂函数,而不是将其定义为一个全局变量. var mxgraph = require("mxgraph")( { // 以下地址不需要修改 mxImageBasePath: "./src/images", mxBasePath: "./src" })

  • vue组件中的样式属性scoped实例详解

    Scoped CSS Scoped CSS规范是Web组件产生不污染其他组件,也不被其他组件污染的CSS规范. vue组件中的style标签标有scoped属性时表明style里的css样式只适用于当前组件元素 它是通过使用PostCSS来改变以下内容实现的: <style scoped> .example { color: red; } </style> <template> <div class="example">hi</di

  • vue缓存之keep-alive的理解和应用详解

    官方解释: <keep-alive> 包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们.和 <transition> 相似,<keep-alive> 是一个抽象组件:它自身不会渲染一个 DOM 元素,也不会出现在组件的父组件链中. 当组件在 <keep-alive> 内被切换,它的 activated 和 deactivated 这两个生命周期钩子函数将会被对应执行. 主要用于保留组件状态或避免重新渲染. keep-alive 是 Vue 的内置组件,

  • Vue之使用mockjs生成模拟数据案例详解

    目录 在项目中安装mockjs 在Vue项目中使用mockjs的基本流程 Mock语法规范 数据模板定义规范(Data Template Definition,DTD) 数据占位符定义规范(Data Placeholder Definition,DPD) Mock.mock() Mock.Random() 在项目中安装mockjs 在项目目录下执行以下安装命令 npm install mockjs --save 在Vue项目中使用mockjs的基本流程 安装完成后,在项目src/utils目录下

随机推荐