VUE.js API

导读:本篇文章讲解 VUE.js API,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com


<div id="app">
    <!--v-bind 属性(判断/赋值),数组运用-->
    <p v-bind:class="{'class1': use}" v-bind:class1="use">{{ message }}</p>
    <div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }">菜鸟教程</div>
    <div v-bind:class="[activeClass, errorClass]"></div>
    <!--div class="active text-danger"></div-->

    <!--v-bind 缩写-->
    <a :href="message">a</a>
    <p>{{details()}}</p>
    <!--js表达式-->
    <div>
      <p>{{5+5}}</p>
      <p>{{use?"YES":NO}}</p>
      <p> {{ message.split('').reverse().join('') }}</p>
    </div>

    <!--指令-->
    <span v-if="use">现在你看到我了</span><span v-else-if="use === '1'"> </span><span v-else> </span>
    <!--事件监听 @缩写-->
    <a v-on:click="details">clcik</a>
    <a @click="details"></a>
    <!--双向数据绑定,复选框可以绑定数组-->
    <input v-model="message">
    <!--lazy绑定chagne事件-->
    <input v-model.lazy="message">
    <!--.number传入值转为number-->
    <input v-model.number="message">
    <!--.trim去首尾空格-->
    <input v-model.trim="message">

    <!--.修饰符,submit后调用prevent-->
    <form v-on:submit.prevent="onSubmit"></form>

    <!-- | 格式化-->
    {{ message | capitalize }}{{ message | capitalize | capitalize }}
    <div v-bind:id="message | capitalize"></div>

    <!--展示元素-->
    <h1 v-show="use">Hello!</h1>

    <ol>
      <li v-for="site in sites">
        {{ site.name }}
      </li>
      <template v-for="site in sites">
        <li>{{ site }}</li>
      </template>
      <li v-for="(value, key) in object">
        {{ key }} : {{ value }}
      </li>
      <li v-for="(value, key, index) in object">
        {{ index }}. {{ key }} : {{ value }}
      </li>
      <li v-for="n in 2">
        {{ n }}
      </li>
    </ol>
    {{details2}}


    <!--事件修饰符-->
    <!-- 阻止单击事件冒泡 -->
    <a v-on:click.stop="doThis"></a>
    <!-- 提交事件不再重载页面 -->
    <form v-on:submit.prevent="onSubmit"></form>
    <!-- 修饰符可以串联  -->
    <a v-on:click.stop.prevent="doThat"></a>
    <!-- 只有修饰符 -->
    <form v-on:submit.prevent></form>
    <!-- 添加事件侦听器时使用事件捕获模式 -->
    <div v-on:click.capture="doThis">...</div>
    <!-- 只当事件在该元素本身(而不是子元素)触发时触发回调 -->
    <div v-on:click.self="doThat">...</div>
    <!-- click 事件只能点击一次,2.1.4版本新增 -->
    <a v-on:click.once="doThis"></a>


    <!--按键修饰符-->
    <input v-on:keyup.13="submit">
    <input v-on:keyup.enter="submit">
    <!-- 缩写语法 -->
    <input @keyup.enter="submit">
    <!-- 按键别名.enter.tab.delete.esc.space.up.down.left.right.ctrl.alt.shift.meta-->



    <!--组件注册,遍历种的传递-->
    <runoob message="hello!" v-bind:message3="message"></runoob>
    <runoob v-for="site in sites" v-bind:message="site.name"></runoob>
    <my-child :mnum="1200" :msg="'sdf'" :object="{a:'a'}" :cust="100">
    </my-child>
    <!--绑定事件-->
    <runoob message="hello!" v-on:click.native="doTheThing"></runoob>

    <script>


      Vue.component('my-child', {
        props: {//type:String,Number,Boolean,Array,Object,Date,Function,Symbol
          num: Number,// 基础类型检测 (`null` 意思是任何类型都可以)
          propB: [String, Number], // 多种类型
          msg: { type: String, required: true },// 必传且是字符串
          num1: { type: Number, default: 1000 },  // 数字,有默认值
          object: {// 数组/对象的默认值应当由一个工厂函数返回
            type: Object,
            default: function () {
              return { message: 'hello' }
            }
          },
          cust: { // 自定义验证函数
            validator: function (value) {
              return value > 10
            }
          }
        },
        template: `<div>
       <p>{{ num }}</p>
       <p>{{ msg }}</p>
       <p>{{ num1 }}</p>
       <p>{{ object }}</p>
       <p>{{ cust }}</p>
      </div>`
      })


      // 注册
      Vue.component('runoob', {
        props: ['message', 'message3'],//声明组件的属性
        template: '<p>{{message}}{{message3}}</p>'
      });
      var data = {
        activeClass: 'active',
        errorClass: 'text-danger',
        activeColor: 'green',
        fontSize: 30,
        message: "hello",
        message2: "",
        use: true,
        sites: [
          { name: 'Runoob' },
          { name: 'Google', sex: "boy" },
          { name: 'Taobao' }
        ],
        object: { name: 'zms', slogan: '程序猿!' }
      };
      var vm = new Vue({
        el: '#app',
        data: data,
        methods: {//在重新渲染的时候,函数总会重新调用执行
          details: function () {
            console.log("details");
            return this.message + " -  details";
          },

        },
        //directive:{}
        //components: { 'runoob': {template:} },//组件注册
        watch: { message: function (value) { } },//值改变触发
        computed: {//依赖缓存,只有相关依赖发生改变时才会重新取值
          details2: function () {
            console.log("details2");
            return this.message.split('').reverse().join('')
          },
          site: {
            get: function () {  // getter
              return this.message + ' ' + this.use
            },
            set: function (newValue) { // setter
              var names = newValue.split(' ')
              this.message = names[0]
              this.message2 = names[names.length - 1]
            }
          }
        },
        filters: {
          capitalize: function (value) {
            if (!value) return ''
            value = value.toString()
            return value.charAt(0).toUpperCase() + value.slice(1)
          }
        }
      })

      // 注册一个全局自定义指令 v-focus
      Vue.directive('focus', {// 当绑定元素插入到 DOM 中。
        //bind: 只调用一次,指令第一次绑定到元素时调用,用这个钩子函数可以定义一个在绑定时执行一次的初始化动作。
        //inserted: 被绑定元素插入父节点时调用(父节点存在即可调用,不必存在于 document 中)。
        //update: 被绑定元素所在的模板更新时调用,而不论绑定值是否变化。通过比较更新前后的绑定值,可以忽略不必要的模板更新(详细的钩子函数参数见下)。
        //componentUpdated: 被绑定元素所在模板完成一次更新周期时调用。
        //unbind: 只调用一次, 指令与元素解绑时调用。
        inserted: function (el) { el.focus() }// 聚焦元素
      })

      vm.site = 'hello word';
      console.log(vm.message2); console.log(vm.message);
      vm.message == data.message;//true
      vm.$el === document.getElementById('app')//$符号的特殊引用
      vm.$watch('message', function (nval, oval) { });//监听属性变化  oval 旧,nval新
    </script>
</div>


    <!--注册事件-->
    <div id="counter-event-example">
      <p>{{ total }}</p>
      <button-counter v-on:incrementa="incrementTotal"></button-counter>
      <button-counter v-on:incrementa="incrementTotal"></button-counter>
    </div>

    <script>
      Vue.component('button-counter', {
        template: '<button v-on:click="incrementHandler">{{ counter }}</button>',
        data: function () {
          return { counter: 0 }
        },
        methods: {
          incrementHandler: function () {
            this.counter += 1
            this.$emit('incrementa')
          }
        },
      })
      new Vue({
        el: '#counter-event-example',
        data: { total: 0 },
        methods: {
          incrementTotal: function () { this.total += 1 }
        }
      })
    </script>
<div id="app">
  <h1>Hello App!</h1>
  <p><!--replace不会留下历史记录,append相对路径-->
!--tag="li" 渲染成某种标签 -->
!--active-class = "_active"激活classs   -->
!--exact-active-class = "_active"-->
!--event = "mouseover" 可以触发导航的事件-->

     <router-link to="/foo" replace append>Go to Foo</router-link>
     <router-link v-bind:to="'bar'">Home</router-link>
     <router-link :to="'home'">Home</router-link> 
     <router-link :to="{ path: 'home' }">Home</router-link>
     <router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>
     <router-link :to="{ path: 'register', query: { plan: 'private' }}">Register</router-link>
 </p>
    <router-view></router-view><!--组件显示区域-->
</div>

<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script> 
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
] 
const router = new VueRouter({
  routes // (缩写)相当于 routes: routes
})
 
const app = new Vue({
  router
}).$mount('#app')
 
</script> 

动画

name 默认有fade,slide-fade

关键字

  • enter 定义进入过渡的开始状态。在元素被插入之前生效
  • enter-active 定义进入过渡生效时的状态
  • enter-to (2.1.8+) 进入过渡的结束状态
  • leave 定义离开过渡的开始状态
  • leave-active 定义离开过渡生效时的状态
  • leave-to (2.1.8+) 定义离开过渡的结束状态

.name-关键字{} 自定义style

关键字-class=”自定义class名/第三方class名” 

duration自定义过度时间  duration={ enter: 500, leave: 800 }设置移入,移出

钩子函数v-on,事件触发调用:methods: {  beforeEnter: function (el) {  }..}

在 enter 和 leave 中必须使用 done 进行回调。否则,它们将被同步调用,过渡会立即完成

<transition name = "fade" 
      enter-class="class1" 
      duration="1000"
      v-on:before-enter="beforeEnter"
      v-on:enter="enter"
      v-on:after-enter="afterEnter"
      v-on:enter-cancelled="enterCancelled"
      v-on:before-leave="beforeLeave"
      v-on:leave="leave"
      v-on:after-leave="afterLeave"
      v-on:leave-cancelled="leaveCancelled"
      
      appear
      appear-class="custom-appear-class"
      appear-to-class="custom-appear-to-class" (2.1.8+)
      appear-active-class="custom-appear-active-class"
      v-on:before-appear="customBeforeAppearHook"
      v-on:appear="customAppearHook"
      v-on:after-appear="customAfterAppearHook"
      v-on:appear-cancelled="customAppearCancelledHook"
>
    <p v-show = "show" v-bind:style = "styleobj">动画实例</p>
</transition>

 

 

      // 也可以通过 params 设置参数:
        axios.get('/user', { params: { ID: 12345 } }).then(function (response) { }).catch(function (error) { });
        //axios.post..

        function axiosA() { return axios.get('...'); }

        function axiosB() { return axios.get('...'); }

        //同是执行,一并结束
        axios.all([axiosA(), axiosB()]).then(axios.spread(function (acct, perms) { }));

        axios({
          method: 'post',
          baseURL: 'http://ww...',
          url: '/...',//baseURL+url 完整路径
          data: {},
          transformRequest: [function (data) { return data; }],//发送前整理数据
          transformResponse: [function (data) { return data; }],//传递给 then/catch 前,允许修改响应数据
          headers: { "X-Requested-With": "XMLHttpRequest" },//自定义请求头
          params: {},//URL参数
          paramsSerializer: function (params) { return Qs.stringify(params, { arrayFormat: "brackets" }) },//负责序列化
          data: {}, //作为请求主体被发送的数据
          timeout: 1000,//超时时间
          withCredentials: false,//跨域请求时是否需要使用凭证
          adapter: function (config) { },  // `adapter` 允许自定义处理请求,以使测试更轻松
          auth: { username: "janedoe", password: "s00pers3cret" },  // 覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头
          responseType: "json", // 服务器响应的数据类型  "arraybuffer", "blob", "document", "json", "text", "stream" 
          xsrfCookieName: "XSRF-TOKEN", //   xsrf token 的值的cookie的名称 
          xsrfHeaderName: "X-XSRF-TOKEN", //   `xsrfHeaderName` 是承载 xsrf token 的值的 HTTP 头的名称
          onUploadProgress: function (progressEvent) { }, // `onUploadProgress` 允许为上传处理进度事件
          onDownloadProgress: function (progressEvent) { }, // `onDownloadProgress` 允许为下载处理进度事件
          // `maxContentLength` 定义允许的响应内容的最大尺寸
          maxContentLength: 2000,
          validateStatus: function (status) { return 200 },//定义对于给定的HTTP 响应状态码 status & gt;= 200 & amp;& amp; status & lt; 300; // 默认的
          maxRedirects: 5, // 定义在 node.js 中 follow 的最大重定向数目
          httpAgent: new http.Agent({ keepAlive: true }),// `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。允许像这样配置选项:
          httpsAgent: new https.Agent({ keepAlive: true }),
          proxy: { host: "127.0.0.1", port: 9000, auth: { username: "mikeymike", password: "rapunz3l" } }, // "proxy" 定义代理服务器的主机名称和端口, `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据
          cancelToken: new CancelToken(function (cancel) {  // 用于取消请求的 cancel token
          })
        }).then(function (response) {
          // { data: { }, status: 200, statusText: "OK", headers: { }, config: { } }
        }).catch(function (error) { }); 

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/107721.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!