-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Vue.js #29
Comments
The Vue InstanceConstructorvar MyComponent = Vue.extend({
// extension options
}) Properties and Methodsvar vm = new Vue({
el: '#example',
data: {
name: 'name'
}
});
vm.name === vm.$data.name // -> true
vm.$data === data // -> true
vm.$el === document.getElementById('example') // -> true
// $watch is an instance method
vm.$watch('a', function (newVal, oldVal) {
// this callback will be called when `vm.a` changes
}); Instance Lifecycle Hooksvar vm = new Vue({
created: function () {},
mounted: function () {},
updated: function () {},
destroyed: function () {},
}); Lifecycle Diagram |
Template SyntaxInterpolationsText<span v-once>This will never change: {{ msg }}</span> Raw HTML<div v-html="rawHtml"></div> Attributes<button v-bind:disabled="someDynamicCondition">Button</button> Using JavaScript Expressions<div v-bind:id="'list-' + id"></div> Filters{{ message | capitalize }}
{{ message | filterA | filterB }}
{{ message | filterA('arg1', arg2) }} new Vue({
// ...
filters: {
capitalize: function (value) {
if (!value) return '';
value = value.toString();
return value.charAt(0).toUpperCase() + value.slice(1);
}
}
}); DirectivesDirectives are special attributes with the ArgumentsSome directives can take an “argument”, denoted by a colon after the directive name. <a v-bind:href="url"> ... </a>
<a v-on:click="doSomething"> ... </a> ModifiersModifiers are special postfixes denoted by a dot, which indicate that a directive should be bound in some special way. <form v-on:submit.prevent="onSubmit"> ... </form> Shorthands
|
Computed Properties and WatchersComputed Properties and Watchers — Vue.js Computed Propertiesvar vm = new Vue({
el: '#example',
data: {
message: 'Hello'
},
computed: {
reversedMessage: function() {
return this.message.split('').reverse().join('');
}
}
}); Watched Propertiesvar vm = new Vue({
el: '#watch-example',
data: {
question: '',
},
watch: {
// whenever question changes, this function will run
question: function (newQuestion) {
this.answer = 'Waiting for you to stop typing...';
this.getAnswer();
}
}
}); |
Class and Style BindingsClass and Style Bindings — Vue.js Binding HTML ClassesObject Syntax<div class="static"
v-bind:class="{ active: isActive, 'text-danger': hasError }">
</div>
<div v-bind:class="classObject"></div> Array Syntax<div v-bind:class="[{ active: isActive }, errorClass]"> Binding Inline StylesObject Syntax<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div> Array Syntax<div v-bind:style="[baseStyles, overridingStyles]"></div> |
Conditional RenderingConditional Rendering — Vue.js
|
List Rendering
|
Event HandlingListening to Events<div id="example-1">
<button v-on:click="counter += 1">Add 1</button>
<p>The button above has been clicked {{ counter }} times.</p>
</div> Method Event Handlers<button v-on:click="greet">Greet</button> Methods in Inline HandlersYou can pass it into a method using the special <button v-on:click="say('hi')">Say hi</button>
<button v-on:click="warn('Form cannot be submitted yet.', $event)">Submit</button> Event ModifiersVue provides event modifiers for
<!-- the click event's propagation will be stopped -->
<a v-on:click.stop="doThis"></a>
<!-- the submit event will no longer reload the page -->
<form v-on:submit.prevent="onSubmit"></form>
<!-- modifiers can be chained -->
<a v-on:click.stop.prevent="doThat"></a>
<!-- just the modifier -->
<form v-on:submit.prevent></form>
<!-- use capture mode when adding the event listener -->
<!-- i.e. an event targeting an inner element is handled here before being handled by that element -->
<div v-on:click.capture="doThis">...</div>
<!-- only trigger handler if event.target is the element itself -->
<!-- i.e. not from a child element -->
<div v-on:click.self="doThat">...</div>
<!-- the click event will be triggered at most once -->
<a v-on:click.once="doThis"></a>
<!-- corresponding to addEventListener‘s passive option -->
<!-- the scroll event's default behavior (scrolling) will happen -->
<!-- immediately, instead of waiting for `onScroll` to complete -->
<!-- in case it contains `event.preventDefault()` -->
<div v-on:scroll.passive="onScroll">...</div> Key Modifiers<input @keyup.enter="submit">
You can also define custom key modifier aliases via the global // enable `v-on:keyup.f1`
Vue.config.keyCodes.f1 = 112; Automatic Key ModifiersYou can also directly use any valid key names exposed via // the handler will only be called if $event.key === 'PageDown'.
<input @keyup.page-down="onPageDown"> System Modifier Keys
<!-- Alt + C -->
<input @keyup.alt.67="clear">
<!-- Ctrl + Click -->
<div @click.ctrl="doSomething">Do something</div>
|
Form Input BindingsValue Bindings<select v-model="selected">
<option v-for="option in options" v-bind:value="option.value">
{{ option.text }}
</option>
</select>
<span>Selected: {{ selected }}</span>
<select v-model="selected">
<!-- inline object literal -->
<option v-bind:value="{ number: 123 }">123</option>
</select>
<span>Selected: {{ selected.number }}</span> Modifiers
|
ComponentsReusing Components
|
Vue Instanceconst vm = new Vue({
el: '#app',
data: {
name: 'Roger',
},
computed: {
now() {
return (new Date()).toString();
},
},
watch: {
name: function(value) {
this.fullName = 'hello ' + value;
},
},
created() {
console.log('vm created');
},
filters: {
lowercase(value) {
return value.toLowerCase();
},
},
components: {
},
methods: {
onAddItem(event) {
console.log('add item');
},
},
}); |
Vue ComponentVue.component('todo-item', {
template: '#item-template',
replace: true,
props: {
name: {
type: String,
required: true,
default() {
return 'Unnamed';
},
validator(value) {
return value.length < 20;
},
},
},
data() {
return {
message: 'hello',
};
},
computed: {
now() {
return (new Date()).toString();
},
},
methods: {
increment() {
this.count += 1;
this.$emit('increment');
},
},
}); |
TransitionsTransitioning Single Elements/Components
Transition Classes
Each of these classes will be prefixed with the name of the transition. If you use
CSS Transitions<div id="example">
<transition name="fade">
<p v-if="show">hello</p>
</div> new Vue({
el: '#example',
data: {
show: true,
},
}); .fade-enter-active, .fade-leave-active {
transition: opacity .5s ease;
}
.fade-enter, .fade-leave-active {
opacity: 0;
} CSS Animations
<div id="example">
<transition name="fade">
<p v-if="show">hello</p>
</div> new Vue({
el: '#example',
data: {
show: true,
},
}); .bounce-enter-active {
animation: bounce-in .5s;
}
.bounce-leave-active {
animation: bounce-out .5s;
}
@keyframes bounce-in {
0% {
transform: scale(0);
}
50% {
transform: scale(1.5);
}
100% {
transform: scale(1);
}
}
@keyframes bounce-out {
0% {
transform: scale(1);
}
50% {
transform: scale(1.5);
}
100% {
transform: scale(0);
}
} Custom Transition Classes
It is useful when you want to combine Vue's transition system with an existing CSS animation library, such as Animate.css. <div id="example">
<transition
name="custom-classes-transition"
enter-active-class="animated tada"
leave-active-class="animated bounceOutRight">
<p v-if="show">hello</p>
</transition>
</div> new Vue({
el: '#example',
data: {
show: true,
},
}); |
Data Binding剖析Vue原理&实现双向绑定MVVM - 云+社区 - 腾讯云 Vue 源码解析:深入响应式原理 · Issue #7 · DDFE/DDFE-blog
|
Vuex
StateThe
|
SSR |
MixinsOption Mergingvar mixin = {
methods: {
foo: function () {
console.log('foo')
},
conflicting: function () {
console.log('from mixin')
}
}
}
var vm = new Vue({
mixins: [mixin],
methods: {
bar: function () {
console.log('bar')
},
conflicting: function () {
console.log('from self')
}
}
})
vm.foo() // => "foo"
vm.bar() // => "bar"
vm.conflicting() // => "from self" |
Custom Directivesdirectives: {
focus: {
// directive definition
inserted: function (el) {
el.focus()
}
}
} <input v-focus> Hook Functions
Directive Hook Arguments
|
Render FunctionsRender Functions & JSX — Vue.js The Virtual DOMrender: function (createElement) {
return createElement('h1', data, children);
} The Data Object{
class: {
foo: true,
bar: true
},
style: {
color: 'red',
fontSize: '14px'
},
attrs: {
id: 'foo'
},
props: {},
domProps: {
innerHTML: 'baz'
},
on: {
click: this.clickHandler
},
nativeOn: {
click: this.nativeClickHandler
},
directives: [
{
name: 'my-custom-directive',
value: '2',
expression: '1 + 1',
}
],
scopedSlots: {
default: props => createElement('span', props.text)
},
slot: 'name-of-slot',
key: 'myKey',
ref: 'myRef'
} VNodes Must Be UniqueInvalid: render: function (createElement) {
var myParagraphVNode = createElement('p', 'hi')
return createElement('div', [
// Yikes - duplicate VNodes!
myParagraphVNode, myParagraphVNode
])
} JSX<anchored-heading :level="1">
<span>Hello</span> world!
</anchored-heading> createElement(
'anchored-heading', {
props: {
level: 1
}
}, [
createElement('span', 'Hello'),
' world!'
]
) import AnchoredHeading from './AnchoredHeading.vue'
new Vue({
el: '#demo',
render: function (h) {
return (
<AnchoredHeading level={1}>
<span>Hello</span> world!
</AnchoredHeading>
)
}
}); Functional ComponentsStateless and instanceless. <template functional>
</template> var EmptyList = { /* ... */ }
var TableList = { /* ... */ }
var OrderedList = { /* ... */ }
var UnorderedList = { /* ... */ }
Vue.component('smart-list', {
functional: true,
props: {
items: {
type: Array,
required: true
},
isOrdered: Boolean
},
render: function (createElement, context) {
function appropriateListComponent () {
var items = context.props.items;
if (items.length === 0) return EmptyList;
if (typeof items[0] === 'object') return TableList;
if (context.props.isOrdered) return OrderedList;
return UnorderedList;
}
return createElement(
appropriateListComponent(),
context.data,
context.children
);
}
}); |
PluginsWriting a PluginPlugins usually add global-level functionality to Vue. A Vue.js plugin should expose an MyPlugin.install = function (Vue, options) {
// 1. add global method or property
Vue.myGlobalMethod = function () {
// something logic ...
}
// 2. add a global asset
Vue.directive('my-directive', {
bind (el, binding, vnode, oldVnode) {
// something logic ...
}
...
})
// 3. inject some component options
Vue.mixin({
created: function () {
// something logic ...
}
...
})
// 4. add an instance method
Vue.prototype.$myMethod = function (methodOptions) {
// something logic ...
}
} Using a Plugin// calls `MyPlugin.install(Vue)`
Vue.use(MyPlugin, { someOption: true })
// When using CommonJS via Browserify or Webpack
var Vue = require('vue');
var VueRouter = require('vue-router');
// Don't forget to call this
Vue.use(VueRouter); |
Filters<!-- in mustaches -->
{{ message | capitalize }}
{{ message | filterA | filterB }}
{{ message | filterA('arg1', arg2) }} <!-- in v-bind -->
<div v-bind:id="rawId | formatId"></div> new Vue({
// ...
filters: {
capitalize: function (value) {
if (!value) return '';
value = value.toString();
return value.charAt(0).toUpperCase() + value.slice(1);
}
}
}); |
Introduction - vue.js
Resources
The text was updated successfully, but these errors were encountered: