vue

package module
v0.0.0-...-ab40c9e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 25, 2017 License: MIT Imports: 5 Imported by: 28

README

gopherjs-vue

VueJS bindings for gopherjs

Usage

Combined the power of Gopherjs and VueJS, you can use golang struct to provide the two-way data-binding context for VueJS, and easily implements the popular browser MVVM models in Go.

Currently ViewModel/Component/Directive/Filter are supported and wrapped in a gopherjs friendly way.

These are the basic rules to use this package:

  • all exported fields of the golang struct would become VueJS Instance's data which can be used in the html to do data binding: v-bind, etc

  • all exported funcs of the golang struct would become VueJS Instance's methods which can be called as html event handler: v-on, etc

  • the golang struct talked above is actually of pointer type and should have an anonymous embeded *js.Object field and the exported fields should have proper js struct tag for bidirectionaly data bindings

Using the debug|dev version of VueJS

This package includes the minified|product version of VueJS code by default, if you want to include the debug|dev version of of VueJS code, please specify buidling tags debug to the gopherjs build cmd as this:

gopherjs build --tags debug main.go

for more details please see the examples.

Basic example

gopherjs code:

package main

import (
    "github.com/gopherjs/gopherjs/js"
    "github.com/oskca/gopherjs-vue"
)

type Model struct {
    *js.Object        // this is needed for bidirectional data bindings
    IntValue   int    `js:"integer"`
    Str        string `js:"str"`
}

// this would be recognized as Inc in html
func (m *Model) Inc() {
    m.IntValue += 1
    println("inc called")
}

// this would be recognized as Repeat in html
func (m *Model) Repeat() {
    m.Str = m.Str + m.Str
}

// this would be recognized as Reset in html
func (m *Model) Reset() {
    m.Str = "a string "
}

func main() {
    m := &Model{
        Object: js.Global.Get("Object").New(),
    }
    // field assignment is required in this way to make data passing works
    m.IntValue = 100
    m.Str = "a string"
    // create the VueJS viewModel using a struct pointer
    vue.New("#app", m)
}

html markup:

<!DOCTYPE html>
<html>

<body>
    <div id="app" v-cloak>
        <div>integer: {{ integer }}
            <input v-model="integer"></input>
        </div>
        <div>str: {{ str }} </div>
        <button v-on:click="Inc">Increase</button>
        <button v-on:click="Repeat">Repeat</button>
        <button v-on:click="Reset">Reset</button>
    </div>
    <script type="text/javascript" src="basic.js"></script>
</body>

</html>

compile and run, then there you are :)

Documentation

Overview

Package composite is an higher level wrapper of gopherjs-vue, by providing a more gopher friendly API, this package tries to hide the JavaScript details for VueJS easy usage in GopherJS world.

Package vue provides gopherjs bindings for VueJS. see func `New` and the examples for detailed usage instructions.

Index

Constants

This section is empty.

Variables

View Source
var Config = &TConfig{
	Object: js.Global.Get("Object").New(),
}

Functions

func Compile

func Compile(template string) (renderFn *js.Object)

Vue.compile( template )

Arguments:

{string} template
Usage:

Compiles a template string into a render function. Only available in the standalone build.

func Delete

func Delete(obj, key interface{})

Vue.delete( object, key )

Arguments:

{Object} object
{String} key
Usage:

Delete a property on an object. If the object is reactive, ensure the deletion triggers view updates. This is primarily used to get around the limitation that Vue cannot detect property deletions, but you should rarely need to use it.

func Mixin

func Mixin(mixin interface{})

Vue.mixin( mixin )

Arguments:

{Object} mixin
Usage:

Apply a mixin globally, which affects every Vue instance created afterwards. This can be used by plugin authors to inject custom behavior into components. Not recommended in application code.

func NextTick

func NextTick(cb func())

Defer the callback to be executed after the next DOM update cycle. Use it immediately after you’ve changed some data to wait for the DOM update.

func Pop

func Pop(obj *js.Object) (idx int)

Remove in the bottom of the array

func Push

func Push(obj *js.Object, any interface{}) (idx int)

Add in the bottom of the array

func Reverse

func Reverse(obj *js.Object) *js.Object

func Set

func Set(obj, key, value interface{})

Vue.set( object, key, value )

Arguments:

{Object} object
{String} key
{*} value
Returns: the set value.

Set a property on an object. If the object is reactive, ensure the property is created as a reactive property and trigger view updates. This is primarily used to get around the limitation that Vue cannot detect property additions.

func Shift

func Shift(obj *js.Object) (idx int)

Remove in the front of the array

func Sort

func Sort(obj *js.Object, sorter func(a, b *js.Object) int) *js.Object

func Splice

func Splice(obj *js.Object, index, howmany int, items ...interface{}) *js.Object

array slice operation index required,position to add to(remove from),negative means reverse howmany required,number of items to remove, 0 means no remove items... optional,add new items to the array

func Unshift

func Unshift(obj *js.Object, any interface{}) (idx int)

Add in the front of the array

func Use

func Use(plugin interface{})

Vue.use( mixin )

Arguments:

{Object | Function} plugin
Usage:

Install a Vue.js plugin. If the plugin is an Object, it must expose an install method. If it is a function itself, it will be treated as the install method. The install method will be called with Vue as the argument. When this method is called on the same plugin multiple times, the plugin will be installed only once.

Types

type Component

type Component struct {
	*ViewModel
}

Component is actually an Extended Vue SubClass, which acts as a Component constructor in VueJS world thus you can use Component.New to create a preConfigured VueJS instance(*ViewModel).

func Extend

func Extend(o *Option) *Component

Vue.extend( options ) Arguments:

{Object} options
Usage:

Create a “subclass” of the base Vue constructor. The argument should be an object containing component options. The special case to note here is the data option - it must be a function when used with Vue.extend().

func GetComponent

func GetComponent(name string) *Component

func NewComponent

func NewComponent(
	vmCreator func() (structPtr interface{}),
	templateStr string,
	replaceMountPoint ...bool,
) *Component

NewComponent creates and registers a named global Component

vmCreator should return a gopherjs struct pointer. see New for more details

func (*Component) New

func (c *Component) New() *ViewModel

New create the component instance

func (*Component) Register

func (c *Component) Register(name string) *Component

Register register Component:c in the global namespace

type CreateElement

type CreateElement func(tagName string, data interface{}, children []interface{}) (vnode *js.Object)

type Directive

type Directive struct {
	*js.Object
}

func NewDirective

func NewDirective(updaterCallBack ...interface{}) *Directive

func (*Directive) Register

func (d *Directive) Register(name string)

func (*Directive) SetBinder

func (d *Directive) SetBinder(fnCallback interface{}) *Directive

func (*Directive) SetUnBinder

func (d *Directive) SetUnBinder(fnCallback interface{}) *Directive

func (*Directive) SetUpdater

func (d *Directive) SetUpdater(fnCallback interface{}) *Directive

type DirectiveBinding

type DirectiveBinding struct {
	*js.Object
	// name: the name of the directive, without the prefix.
	Name string `js:"name"`
	// value: The value passed to the directive. For example in v-my-directive="1 + 1", the value would be 2.
	Value string `js:"value"`
	// oldValue: The previous value, only available in update and componentUpdated. It is available whether or not the value has changed.
	OldValue string `js:"oldValue"`
	// expression: the expression of the binding, excluding arguments and filters.
	Expression string `js:"expression"`
	// arg: the argument, if present.
	Arg string `js:"arg"`
	// modifiers: an object containing modifiers, if any.
	Modifiers *js.Object `js:"modifiers"`
}

type DirectiveCallback

type DirectiveCallback func(el *dom.Element, b *DirectiveBinding, vNode, oldVnode *js.Object)

DirectiveCallback can be used in every directive callback functions

type Filter

type Filter func(oldValue *js.Object) (newValue interface{})

Filter return interface{} to utilize GopherJS type convertion automatically

func NewFilter

func NewFilter(fn func(oldValue *js.Object) (newValue interface{})) Filter

using interface{} type here to utilize GopherJS type convertion automatically

func (Filter) Register

func (f Filter) Register(name string)

type LifeCycleEvent

type LifeCycleEvent string
const (
	EvtBeforeCreate  LifeCycleEvent = "beforeCreate"
	EvtCreated       LifeCycleEvent = "created"
	EvtBeforeMount   LifeCycleEvent = "beforeMount"
	EvtMounted       LifeCycleEvent = "mounted"
	EvtBeforeUpdate  LifeCycleEvent = "beforeUpdate"
	EvtUpdated       LifeCycleEvent = "updated"
	EvtActivated     LifeCycleEvent = "activated"
	EvtDeactivated   LifeCycleEvent = "deactivated"
	EvtBeforeDestroy LifeCycleEvent = "beforeDestroy"
	EvtDestroyed     LifeCycleEvent = "destroyed"
)

type Option

type Option struct {
	*js.Object

	// Type: String
	// Restriction: only respected when used in Vue.extend().
	// Details:
	//
	// Allow the component to recursively invoke itself in its template.
	// Note that when a component is registered globally with
	// Vue.component(), the global ID is automatically set as its name.
	//
	// Another benefit of specifying a name option is console inspection.
	// When inspecting an extended Vue component in the console,
	// the default constructor name is VueComponent,
	// which isn’t very informative. By passing in an optional name option to
	// Vue.extend(), you will get a better inspection output so that
	// you know which component you are looking at.
	// The string will be camelized and used as the component’s constructor name.
	Name string `js:"name"`

	// 	Type: Object | Function
	//
	// Restriction: Only accepts Function when used in a component definition.
	//
	// Details:
	//
	// The data object for the Vue instance. Vue.js will recursively convert
	// its properties into getter/setters to make it “reactive”. The object
	// must be plain: native objects, existing getter/setters and prototype
	// properties are ignored. It is not recommended to observe complex
	// objects.
	//
	// Once the instance is created, the original data object can be accessed
	// as vm.$data. The Vue instance also proxies all the properties
	// found on the data object.
	//
	// Properties that start with _ or $ will not be proxied on the Vue
	// instance because they may conflict with Vue’s internal properties and
	// API methods. You will have to access them as vm.$data._property.
	//
	// When defining a component, data must be declared as a function that
	// returns the initial data object, because there will be many instances
	// created using the same definition. If we still use a plain object for
	// data, that same object will be shared by reference across all instance
	// created! By providing a data function, every time a new instance
	// is created, we can simply call it to return a fresh copy of
	// the initial data.
	//
	// If required, a deep clone of the original object can be obtained by
	// passing vm.$data through JSON.parse(JSON.stringify(...)).
	Data interface{} `js:"data"`

	// Type: String | HTMLElement | Function
	// Restriction: only accepts type Function when used in a component definition.
	//
	//Details:
	//
	// Provide the Vue instance an existing DOM element to mount on.
	// It can be a CSS selector string, an actual HTMLElement,
	// or a function that returns an HTMLElement.
	// Note that the provided element merely serves as a mounting point;
	// it will be replaced if a template is also provided,
	// unless replace is set to false. The resolved element will
	// be accessible as vm.$el.
	//
	// When used in Vue.extend, a function must be provided
	// so each instance gets a separately created element.
	// If this option is available at instantiation,
	// the instance will immediately enter compilation;
	// otherwise, the user will have to explicitly call
	// vm.$mount() to manually start the compilation.
	El interface{} `js:"el"`

	// Type: String
	//
	// Details:
	//
	// A string template to be used as the markup for the Vue instance. By
	// default, the template will replace the mounted element. When the replace
	// option is set to false, the template will be inserted into the mounted
	// element instead. In both cases, any existing markup inside the mounted
	// element will be ignored, unless content distribution slots are present
	// in the template.
	//
	// If the string starts with # it will be used as a querySelector and use
	// the selected element’s innerHTML as the template string. This allows the
	// use of the common <script type="x-template"> trick to include templates.
	Template string `js:"template"`

	// parent
	//
	// Type: Vue instance
	//
	// Details:
	//
	// Specify the parent instance for the instance to be created. Establishes
	// a parent-child relationship between the two. The parent will be
	// accessible as this.$parent for the child, and the child will be pushed
	// into the parent’s $children array.
	Parent *js.Object `js:"parent"`

	// delimiters
	//
	// Type: Array<string>
	//
	// default: ["{{", "}}"]
	//
	// Details:
	//
	// Change the plain text interpolation delimiters.
	// This option is only available in the standalone build.
	Delimiters []string `js:"delimiters"`

	// functional
	// Type: boolean
	// Details:
	// 	Causes a component to be stateless (no data) and
	// 	instanceless (no this context).
	// 	They are simply a render function that returns virtual nodes
	// 	making them much cheaper to render.
	Functional []string `js:"functional"`
	// contains filtered or unexported fields
}

Option is used to config VueJS instance or to create VueJS components.

func NewOption

func NewOption() *Option

func (*Option) AddComputed

func (o *Option) AddComputed(name string, getter func(vm *ViewModel) interface{}, setter ...func(vm *ViewModel, val *js.Object))

AddComputed set computed data

func (*Option) AddMethod

func (o *Option) AddMethod(name string, fn func(vm *ViewModel, args []*js.Object)) *Option

AddMethod adds new method `name` to VueJS intance or component using mixins thus will never conflict with Option.SetDataWithMethods

func (*Option) AddProp

func (c *Option) AddProp(name ...string) *Option

AddProp add props to the genereated VueJS instance (optional)

props is a list/hash of attributes that are exposed to accept data from
the parent component. It has a simple Array-based syntax and
an alternative Object-based syntax that allows advanced configurations
such as type checking, custom validation and default values.

func (*Option) AddSubComponent

func (c *Option) AddSubComponent(name string, sub *Component) *Option

AddComponent add sub component to the genereated VueJS instance (optional)

func (*Option) Mixin

func (c *Option) Mixin(val js.M) *Option

The mixins option accepts an array of mixin objects. These mixin objects can contain instance options just like normal instance objects, and they will be merged against the eventual options using the same option merging logic in Vue.extend(). e.g. If your mixin contains a created hook and the component itself also has one, both functions will be called.

Mixin hooks are called in the order they are provided, and called before the component’s own hooks.

func (*Option) NewComponent

func (o *Option) NewComponent() *Component

func (*Option) NewViewModel

func (o *Option) NewViewModel() *ViewModel

NewViewModel create the VueJS instance for finally use the VueJS instance becomes usable only after this call

func (*Option) OnLifeCycleEvent

func (o *Option) OnLifeCycleEvent(evt LifeCycleEvent, fn func(vm *ViewModel)) *Option

func (*Option) SetDataWithMethods

func (c *Option) SetDataWithMethods(structPtr interface{}) *Option

SetDataWithMethods set data and methods of the genereated VueJS instance based on `structPtr` and `js.MakeWrapper(structPtr)`

func (*Option) SetRender

func (o *Option) SetRender(r Render)

type Render

type Render func(vm *ViewModel, fn CreateElement)

type TConfig

type TConfig struct {
	*js.Object
	// Suppress all Vue logs and warnings.
	Silent bool `js:"silent"`
	// The merge strategy receives the value of that option defined on the parent and child instances as the first and second arguments, respectively.
	OptionMergeStrategies interface{} `js:"optionMergeStrategies"`
	// Configure whether to allow vue-devtools inspection.
	Devtools bool `js:"devtools"`
	// Assign a handler for uncaught errors during component render and watchers.
	ErrorHandler func(err, vm *js.Object) `js:"errorHandler"`
	// Make Vue ignore custom elements defined outside of Vue (e.g., using the Web Components APIs).
	IgnoredElements []string `js:"ignoredElements"`
	// Define custom key alias(es) for v-on.
	KeyCodes map[string]int `js:"keyCodes"`
}

TConfig is used for declaration only

type ViewModel

type ViewModel struct {
	*js.Object
	///////////////////////////// Instance Properties
	// vm.$data
	// 	Type: Object
	// Details:
	//  The data object that the Vue instance is observing.
	//  You can swap it with a new object.
	//  The Vue instance proxies access to the properties on its data object.
	Data *js.Object `js:"$data"`

	// vm.$el
	//  Type: HTMLElement
	//  Read only
	// Details:
	//  The DOM element that the Vue instance is managing.
	//	Note that for Fragment Instances, vm.$el will
	//  return an anchor node that
	//	indicates the starting position of the fragment.
	El *js.Object `js:"$el"`

	// vm.$options
	//  Type: Object
	//  Read only
	// Details:
	//  The instantiation options used for the current Vue instance.
	//  This is useful when you want to include custom
	//  properties in the options:
	//	 new Vue({
	//	   customOption: 'foo',
	//	   created: function () {
	//	     console.log(this.$options.customOption) // -> 'foo'
	//	   }
	//	 })
	Options *js.Object `js:"$options"`

	// vm.$parent
	//  Type: Vue instance
	//  Read only
	// Details:
	// 		The parent instance, if the current instance has one.
	Parent *js.Object `js:"$parent"`

	// vm.$root
	//  Type: Vue instance
	//  Read only
	// Details:
	// 		The root Vue instance of the current component tree.
	// 		If the current instance has no parents this value will be itself.
	Root *js.Object `js:"$root"`

	// vm.$children
	//  Type: Array<Vue instance>
	//  Read only
	// Details:
	// 	The direct child components of the current instance.
	Children *js.Object `js:"$children"`

	// vm.$slots
	// 	Type: { [name: string]: ?Array<VNode> }
	// Read only
	// Details:
	// 	Used to programmatically access content distributed by slots.
	//  Each named slot has its own corresponding property
	// 	Accessing vm.$slots is most useful when writing a component with a render function.
	Slots *js.Object `js:"$slots"`

	// vm.$refs
	// 	Type: Object
	// 	Read only
	// Details:
	// 	An object that holds child components that have v-ref registered.
	// See also:
	// 	Child Component Refs
	// 	v-ref.
	Refs *js.Object `js:"$refs"`

	// vm.$isServer
	// Type: boolean
	// Read only
	// Details:
	// Whether the current Vue instance is running on the server.
	IsServer bool `js:"$isServer"`

	// vm.$watch( expression, callback, [deep, immediate] )
	//  expression String
	//  callback( newValue, oldValue ) Function
	//  deep Boolean optional
	//  immdediate Boolean optional
	// Watch an expression on the Vue instance for changes.
	// The expression can be a single keypath or actual expressions:
	WatchEx func(
		expression string,
		callback func(newVal, oldVal *js.Object),
		deepWatch bool,
	) (unwatcher func()) `js:"$watch"`

	// vm.$set( keypath, value )
	// 	keypath String
	// 	value *
	// Set a data value on the Vue instance given a valid keypath.
	// If the path doesn’t exist it will be created.
	Set func(keypath string, val interface{}) `js:"$set"`

	// vm.$delete( keypath )
	// 	keypath String
	// Delete a root level property on the Vue instance (and also its $data).
	Delete func(keypath string) `js:"$delete"`

	// vm.$on( event, callback )
	// 	event String
	// callback Function
	//
	// Listen for an event on the current vm
	On func(event string, callback interface{}) `js:"$on"`

	// vm.$once( event, callback )
	// 	event String
	// callback Function
	//
	// Attach a one-time only listener for an event.
	Once func(event string, callback interface{}) `js:"$once"`

	// vm.$off( [event, callback] )
	// 	event String optional
	// callback Function optional
	//
	// If no arguments are given, stop listening for all events;
	// if only the event is given, remove all callbacks for that event;
	// if both event and callback are given,
	// remove that specific callback only.
	Off func(event ...string) `js:"$off"`

	// vm.$emit( event, [args…] )
	// 	event String
	// args… optional
	//
	// Trigger an event on this vm only.
	Emit func(event string, args ...interface{}) `js:"$emit"`

	// vm.$mount( [element|selector] )
	// 	element HTMLElement | selector String optional
	// If the Vue instance didn’t get an el option at instantiation,
	// you can manually call $mount() to assign an element to it and
	// start the compilation. If no argument is provided,
	// an empty <div> will be automatically created. Calling $mount()
	// on an already mounted instance will have no effect.
	// The method returns the instance itself so you can chain other
	// instance methods after it.
	Mount func(elementOrselector ...interface{}) *js.Object `js:"$mount"`

	// vm.$forceUpdate()
	// Usage:
	// Force the Vue instance to re-render.
	// Note it does not affect all child components,
	// only the instance itself and child components with inserted slot content.
	ForceUpdate func() `js:"$forceUpdate"`

	// vm.$nextTick( [callback] )
	// Arguments:
	// {Function} [callback]
	// Usage:
	// Defer the callback to be executed after the next DOM update cycle. Use it immediately after you’ve changed some data to wait for the DOM update. This is the same as the global Vue.nextTick, except that the callback’s this context is automatically bound to the instance calling this method.
	NextTick func(cb func()) `js:"$nextTick"`

	// vm.$destroy( [remove] )
	//  remove Boolean optional
	// Completely destroy a vm.
	// Clean up its connections with other existing vms,
	// unbind all its directives and remove its $el from the DOM.
	// Also, all $on and $watch listeners will be automatically removed.
	Destroy func(remove bool) `js:"$destroy"`
}

type Vue represents the JavaScript side VueJS instance or VueJS component

func GetVM

func GetVM(structPtr interface{}) *ViewModel

GetVM returns coresponding VueJS instance from a gopherjs struct pointer (the underlying ViewModel data), this function is mainly in gopherjs struct method functions to reference the `VueJS instance`

func New

func New(selectorOrHTMLElement interface{}, structPtr interface{}) *ViewModel

New creates a VueJS Instance to apply bidings between `structPtr` and `selectorOrElementOrFunction` target, it also connects the generated VueJS instance with the `structPtr`, you can use `vue.GetVM` from you code to get the generated VueJS Instance which can be used as `this` for JavaScirpt side.

  • all `exported fields` of the `struct` would become VueJS Instance's data which can be used in the html to do data binding: v-bind, etc

  • all `exported funcs` of the `struct` would become VueJS Instance's methods which can be called as html event handler: v-on, etc

  • the `struct` talked above should have an embeded anonymous `*js.Object` field and `exported fields` should have proper `js struct tag` for bidirectionaly data bindings

  • if the `struct` has no embeded anonymous `*js.Object`, it can only be used for information displaying purpose.

Rules for exported functions usage IMPORTANT!:

  • If your func uses any of the `exported fields`, then DONOT modify any. These can be viewed roughly as `computed attribute` in `VueJS` wourld, with the form of function invocation (invoke).

  • If your func modifies any of the `exported fields`, then DONOT use it in any data `DISPLAYing` expression or directive. They can be used as event handlers (their main use cases).

These rules are required for VueJS dependency system to work correctly.

You can get this *ViewModel instance through `vue.GetVM(structPtr)` which acts as `this` of the VueJS(javascript) side of world

func (*ViewModel) FromJS

func (v *ViewModel) FromJS(obj *js.Object) *ViewModel

FromJS set the corresponding VueJS data model field from obj new data model field will be created when not exist

func (*ViewModel) FromJSON

func (v *ViewModel) FromJSON(jsonStr string) *ViewModel

func (*ViewModel) ToJS

func (v *ViewModel) ToJS() *js.Object

func (*ViewModel) ToJSON

func (v *ViewModel) ToJSON() string

func (*ViewModel) Watch

func (v *ViewModel) Watch(expression string, callback func(newVal *js.Object)) (unwatcher func())

Watch using a simpler form to do Vue.$watch

Directories

Path Synopsis
examples
jscode

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL